<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
div{
width:200px;
height:50px;
background-color:red;
margin:30px;
padding:0;
}
</style>
</head>
<body>
<div class="demo1"></div>
<div class="demo2"></div>
<div class="demo3"></div>
<script>
window.onload=function(){
var div=document.getElementsByTagName('div');
for(var i=0;i<div.length;i++){
div[i].timer=null;
div[i].onmouseover=function(){
startMove(this,500);
};
div[i].onmouseout=function(){
startMove(this,200);
};
}
}
// var timer=null;
function startMove(obj,target){
//单个定时器存在问题
//改变div宽度
//多个物体运动的时候 会共享一个定时器的问题导致物体还没运动到目的地
//定时器因为鼠标移动到其他物体,导致之前的定时器被干掉 因为每个start Move()的定时器前面都有一个clearInterval()
//办法 多开几个定时器-->每个物体的定时器各自独立
var speed=0;
clearInterval(obj.timer);
//匀速运动时候
// obj.timer=setInterval(function(){
// if(obj.offsetWidth>target){
// speed=-7;
// }else{
// speed=7;
// }
// if(Math.abs(target-obj.offsetWidth)<=7){
// clearInterval(obj.timer);
// obj.style.width=target+'px';
// console.log(obj.style.width);//检测是否到达目标地址
// }else{
// obj.style.width=obj.offsetWidth+speed+'px';
// console.log(obj.offsetWidth);
// }
// },100);
//加速运动时候
//记得给速度取整数不然怎么也到不了目的地 造成跳动
timer=setInterval(function(){
var speed=0;
speed=(target-obj.offsetWidth)/6;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(target==obj.offsetWidth){
clearInterval(obj.timer);
}else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},100);
}
</script>
</body>
</html>