<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>多物体动画效果</title>
<style type="text/css">
* {
margin: 0;
padding: 0;
}
ul li {
list-style: none;
}
ul li {
width: 200px;
height: 100px;
background-color: yellow;
margin-bottom: 20px;
border: 10px solid red;
opacity: 0.3;
}
</style>
<script type="text/javascript">
window.onload = function() {
var arrLi = document.getElementsByTagName("li");
for (var i = 0; i < arrLi.length; i++) {
arrLi[i].onmouseover = function() {
startMove(this, {
width: 400,
opacity: 70,
height: 300,
});
};
arrLi[i].onmouseout = function() {
startMove(this, {
width: 200,
opacity: 30,
height: 100,
});
};
}
};
function startMove(obj, json) {
var speed;
var icur;
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var flag = true;
for (var attr in json) {
if (attr === "opacity") {
icur = Math.round(parseFloat(getStyle(obj, attr)) * 100);
} else {
icur = parseInt(getStyle(obj, attr));
}
speed = (json[attr] - icur) / 10;
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
console.log("属性" + attr + ":" + json[attr] + "---icur:" + icur);
if (json[attr] != icur) {
flag = false;
}
if (attr === "opacity") {
obj.style.opacity = (icur + speed) / 100;
// obj.style.filter = "alpha(opacity:" + (icur + speed) + ")";
} else {
obj.style[attr] = icur + speed + "px";
}
if (flag) {
clearInterval(obj.timer);
}
}
}, 30);
}
function getStyle(obj, attr) {
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, null)[attr];
}
}
</script>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>这段代码执行到for中, 有一个属性到达了目标值, 比如width=400, 然后这个时候for遍历结束了, 然后再次执行setInterval()部分, 又遍历for, 进去flag刚开始是true 遇到width=400,不执行这段代码if (json[attr] != icur) { flag = false; }flag 依旧为true, 这个时候清楚interval. 请问会不会这样需要把if (flag) { clearInterval(obj.timer); }这段代码写在for{}后吗? 请问该怎么解决? 谢谢给位【码友】
2 回答
stone310
TA贡献361条经验 获得超191个赞
必须要放在for(){}后面,你这里写的是放在for里面了,目前情况执行没有问题,但是目标值改下就会出问题
arrLi[i].onmouseover = function() { startMove(this, { width: 400, //将400改成201
写在for里面其实跟没写一样,当遍历到其中一个达到目标值,就全部停止,所以要放到for遍历外
添加回答
举报
0/150
提交
取消