------------恢复内容开始------------
多种物体同时运动:
例子:多个Div,鼠标移入变宽
单定时器,存在问题
每个Div一个定时器
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 100px; height: 30px; background: red; margin: 10px; } </style> <script> window.onload = function () { var oDiv =document.getElementsByTagName('div');//获取所有的div for (let i = 0; i < oDiv.length; i++) {//循环出所有的div oDiv[i].time = null;//给每个div加一个定时器。解决:单个定时器,出现的问题 oDiv[i].onmouseover = function(){ starMove(this,400); }; oDiv[i].onmouseout = function (){ starMove(this,100) } } } function starMove(obj,iTarget){ clearInterval(obj.time);//停止每个div的定时器 obj.time = setInterval(function(){ var speed = (iTarget-obj.offsetWidth)/6;//div的运行速度 speed = speed>0?Math.ceil(speed):Math.floor(speed);//速度值的上下取整 if(obj.offsetWidth == iTarget){//判断div的宽度是否等于目标点 clearInterval(obj.time);//如果等于目标点就清除定时器 }else{ //反之 obj.style.width = obj.offsetWidth+speed+'px'; } },30) } </script> </head> <body> <div></div> <div></div> <div></div> </body> </html>
多物体运动框架
定时器作为物体的属性
参数的传递:物体、目标值
例子:多个Div淡入淡出
所有东西都不能共用
属性与运动对象绑定:速度、其他属性值(如透明度)
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div{ width: 200px; height: 100px; margin: 20px; float: left; background: red; filter: opacity(30); opacity: 0.3; } </style> <script> window.onload = function () { var oDiv = document.getElementsByTagName('div'); for(var i = 0;i<oDiv.length;i++){ oDiv[i].alpha = 30; oDiv[i].onmouseover = function(){ startMove(this,100); }; oDiv[i].onmouseout = function(){ startMove(this,30); } } } //var alpha = 30;所有的东西都不能公用 function startMove (obj,iTarget) { clearInterval(obj.time); obj.time = setInterval(function(){ var speed = (iTarget-obj.alpha)/6; speed = speed>0?Math.ceil(speed):Math.floor(speed); if (obj.alpha == iTarget) { clearInterval(obj.time); } else { obj.alpha+=speed; obj.style.filter = 'alpha(opacity:'+obj.alpha+')'; obj.style.opacity = obj.alpha/100; } },30) } </script> </head> <body> <div></div> <div></div> <div></div> <div></div> </body> </html>