【问题标题】:Gradually changing opacity with JavaScript doesn't work用 JavaScript 逐渐改变不透明度不起作用
【发布时间】:2019-12-01 23:11:32
【问题描述】:

我有这个元素:

<div id="newDimention">
  <div class="newDimention">
  </div>
</div>  

我正在尝试使用 javascript 更改其不透明度:

let newDimention=document.getElementById('newDimention');
setTimeout(()=>{
 setDimention();
  newDimention.innerText="You've uncovered the third dimension."
   newDimention.style.color="purple";
    newDimention.style.fontSize='30px';
    newDimention.style.marginTop='30px';
    newDimention.style.opacity="0";
    })



const setDimention = () => {
for (var i = 0,b=14; i <= 500; i++) {
 setTimeout(()=>{
//document.getElementById("newDimention").style.opacity=String(Math.round(i/50)/10);
   newDimention.style.opacity=String(Math.round(i/50)/10);
 },i*b)
}
}

我尝试不转换为字符串,尝试通过类 id 访问。 Devtools 清楚地表明String(Math.round(i/50)/10) 每次都会逐渐增加。但是newDimention.style.opacity 每次都保持'0'

然后一旦String(Math.round(i/50)/10)==='1'newDimention.style.opacity 立即更改为'1'。所以它出于某种原因一直保持'0',直到i===500,然后突然变为'1'。我没有任何其他函数来操作这个元素。如果我删除newDimention.style.opacity=String(Math.round(i/50)/10); 行,不透明度将保持在'0',所以这条线应该改变这个元素的不透明度。

为什么会这样?

【问题讨论】:

    标签: javascript html css opacity


    【解决方案1】:

    在写这个问题时,我意识到我在for loop 中使用了var 而不是let,所以当函数最终在setTimeout 之后被触发时,它们使用了最新值i===500。将其更改为 let 已修复:

    const setDimention = () => {
    for (let i = 0,b=14; i <= 500; i++) {
     setTimeout(()=>{
    //document.getElementById("newDimention").style.opacity=String(Math.round(i/50)/10);
       newDimention.style.opacity=String(Math.round(i/50)/10);
     },i*b)
    }
    }
    

    来自https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let

    "let 允许您声明仅限于块语句或使用它的表达式的范围内的变量,这与 var 关键字不同,后者在全局范围内或本地定义整个函数的变量,而不管块范围”。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2016-08-20
      • 2012-12-09
      • 1970-01-01
      • 2013-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多