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

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

如有答复将不胜感激:)

最佳答案

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/

相关文章:

html - 构建由流体填充分隔的 2 个固定宽度列的跨浏览器方法是什么?

css - 修复了全宽 CSS header 无法在窄浏览器窗口中正确滚动的问题

javascript - 如何通过点击事件来改变图像?

javascript - 获取字符串、提取 id 并换行文本

javascript - js 和 d3 中给定键的返回值 - 我必须循环吗?

javascript - "typeError: Cannot read property ' 用户名 ' of undefined."

javascript - 当用户点击按钮时弹出一个窗口

html - 将 css 文件绑定(bind)到 ReactJs 中的组件,例如 Angular 2+

css - 带有渐变背景的 IE8 中表格标题边框消失

css - Webpack 构建成功但 styles.css 文件样式未反射(reflect)