代码只在循环结束时改变元素的高度值,这意味着没有动画:,(
代码如下:
function heightenElement(id,interval,step,height,unit) {
y = 0;
function loop() {
y = y + step;
thing = y + unit;
console.log(y);
if (y < height) {
document.getElementById(id).style.height = thing;
setTimeout(loop(),interval);
}
}
loop();
}
如有答复将不胜感激:)
最佳答案
setTimeout
接受一个函数作为参数 - 如果您在其中放置一个函数 call,该函数将立即执行。只需传递函数名称即可:
function heightenElement(id, interval, step, height, unit) {
let y = 0;
function loop() {
y = y + step;
thing = y + unit;
console.log(y);
if (y < height) {
document.getElementById(id).style.height = thing;
setTimeout(loop, interval);
}
}
loop();
}
heightenElement('div', 500, 10, 100, 'px');
div {
height: 30px;
background-color: yellow;
}
<div id="div">
</div>
关于javascript - 无法使用循环更改 element.style.height 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50171708/