我想建立一个加载div。它的宽度应以其宽度的1%的0.01秒增长。
我的代码:
const btn = document.querySelector('button');
const div = document.querySelector('div');
div.style.width = `0%`;
const loading = () => {
let divWidth = 0;
function load() {
divWidth++;
div.style.width = `${divWidth}%`;
}
if (divWidth <= 100) {
setTimeout(load, 100);
}
};
btn.addEventListener('click', loading);
答案 0 :(得分:0)
使用setInterval代替setTimeout
const btn = document.querySelector('button');
const div = document.querySelector('div');
div.style.width = `0%`;
const loading = () => {
let divWidth = 0;
function load() {
divWidth++;
div.style.width = `${divWidth}%`;
if(divWidth >= 100) clearInterval(loader);
}
const loader = setInterval(load, 100);
};
btn.addEventListener('click', loading);
.growing-div {
height: 100px;
background: blue;
}
<button>Button</button>
<div class="growing-div">Div</div>
答案 1 :(得分:-1)
尝试一下
const btn = document.querySelector('button');
const div = document.querySelector('div');
div.style.width = "0%";
var divWidth = 0;
function a() {
divWidth++;
// console.log(divWidth)
div.style.width = `${divWidth}%`;
if (divWidth <= 100) {
setTimeout(a, 100);
}
}
div {
border: 1px solid yellow;
background-color:purple;
color:white;
}
<div>loading....</div>
<button onclick="a()">click</button>