无法使用循环更改element.style.height值

时间:2018-05-04 09:33:51

标签: javascript html css

代码只会在循环结束时更改元素的高度值,这意​​味着没有动画:,(

代码如下:

 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();
 }

答案将不胜感激:)

1 个答案:

答案 0 :(得分:3)

setTimeout接受一个函数作为参数 - 如果你在其中放置一个函数 call ,该函数将立即执行。只需传递函数名称:

&#13;
&#13;
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');
&#13;
div {
  height: 30px;
  background-color: yellow;
}
&#13;
<div id="div">
</div>
&#13;
&#13;
&#13;