JS setInterval()只触发一次

时间:2016-03-11 02:19:35

标签: javascript

<html>

<head>
  <script type="text/javascript">
    function topdiv() {
      var z = document.createElement("DIV");
      z.id = "top";
      z.style = "background-color:yellow; width:100%; height:50px; opacity: 1.0";
      z.class = "top";
      document.body.appendChild(z);
    }

    function animateDiv() {
      var d = document.getElementById("top");
      if (d.style.opacity == "0.0") {
        d.style.opacity = "1.0";
      } else {
        d.style.opacity = "0.0";
      }
    }
  </script>
</head>

<body onload="topdiv()">
  <script type="text/javascript">
    var xyz = setInterval(function() {
      animateDiv()
    }, 300);
  </script>
</body>

</html>

我在代码中使用setInterval在30 ms后不断更改div的不透明度,但该函数只执行一次。有人可以帮我解决一下吗?

2 个答案:

答案 0 :(得分:1)

变化

if (d.style.opacity == "0.0") 

为:

if (d.style.opacity === "0") 

http://plnkr.co/edit/eWFDo9OJrYzK3ahz1EBG?p=preview

答案 1 :(得分:0)

由于您使用CSS设置初始不透明度,因此您需要查看计算样式。而不是那样做;在元素本身的代码中设置不透明度。

以防浏览器确实返回字符串值,在比较之前将其强制转换为数字。您还可以将不透明度设置为数字。

看看这个:

&#13;
&#13;
<html>

<head>
  <script type="text/javascript">
    function topdiv() {
      var z = document.createElement("DIV");
      z.id = "top";
      z.style = "background-color:yellow; width:100%; height:50px; opacity: 1.0";
      z.style.opacity = 1;
      z.class = "top";
      document.body.appendChild(z);
    }

    function animateDiv() {
      var d = document.getElementById("top");
      if (+d.style.opacity == 0) {
        d.style.opacity = 1;
      } else {
        d.style.opacity = 0;
      }
    }
  </script>
</head>

<body onload="topdiv()">
  <script type="text/javascript">
    var xyz = setInterval(function() {
      animateDiv()
    }, 300);
  </script>
</body>

</html>
&#13;
&#13;
&#13;