1

我也尝试过从 jQuery 编写类似于 fadeOut 的简单函数,但卡住了。一切正常,但不透明度从 0.02 而不是从 1 降低,正如我在 css 中所写的那样。通过 console.log() 检查代码在第一步显示为空,然后是 -0.02,-0,04。这是我的代码css:

#box {
  background: red;
  height: 200px;
  opacity:1;
  width: 200px;
}

JS:

 var box = document.getElementById("box");

 setInterval(function() {
  console.log(box.style.opacity);
  box.style.opacity -= 0.02;
 }, 1000)

这是codepen http://codepen.io/Kuzyo/pen/xDc 有人可以解释发生了什么。谢谢。

4

2 回答 2

3

window.getComputedStyle()阅读 CSS 属性时需要。

 box.style.opacity = window.getComputedStyle(box).opacity - 0.02;

演示:http: //jsfiddle.net/aCKNz/

于 2013-07-28T06:45:57.130 回答
1

element.style.opacity只有在元素的属性中定义样式时才响应样式style="...",而不是在样式表中。

试试这个:

var box = document.getElementById('box');
(function(){var o=1;setTimeout(function(){box.style.opacity=o-=0.2;if(o>0)setTimeout(arguments.callee,1000);},1000);})();

或者,以其扩展形式:

var box = document.getElementById('box');
(function(){
    var o=1;
    setTimeout(function(){
        o -= 0.2;
        box.style.opacity = o;
        if(o>0) setTimeout(arguments.callee,1000);
    },1000);
})();
于 2013-07-28T06:47:55.527 回答