<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的不透明度,但该函数只执行一次。有人可以帮我解决一下吗?
答案 0 :(得分:1)
变化
if (d.style.opacity == "0.0")
为:
if (d.style.opacity === "0")
答案 1 :(得分:0)
由于您使用CSS设置初始不透明度,因此您需要查看计算样式。而不是那样做;在元素本身的代码中设置不透明度。
以防浏览器确实返回字符串值,在比较之前将其强制转换为数字。您还可以将不透明度设置为数字。
看看这个:
<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;