<!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{}后吗? 请问该怎么解决? 谢谢给位【码友】
stone310
相关分类