<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>链式同步运动</title>
<style type="text/css">
#div1 {
margin:0 auto;
width:200px;
height:200px;
background:red;
filter:alpha(opacity=100);
opacity:1;
}
#div2 {
margin:20px auto;
width:200px;
height:200px;
background:green;
filter:alpha(opacity=100);
opacity:1;
}
</style>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
<script type="text/javascript">
var div1 = document.getElementById("div1");
var div2 = document.getElementById("div2");
div1.onmouseover = function() {
change(this,{"width":400,"height":300,"opacity":20},function() {
change(this,{"width":200,"height":200,"opacity":100},function() {
change(this,{"width":400,"height":400,"opacity":10});
})
})
}
div1.onmouseout = function() {
change(this,{"width":400,"height":300,"opacity":20},function() {
change(this,{"width":300,"height":300,"opacity":60},function() {
change(this,{"width":200,"height":200,"opacity":100});
})
})
}
div2.onmouseover = function() {
change(this,{"width":400,"height":300,"opacity":10},function() {
change(this,{"width":200,"height":200,"opacity":100},function() {
change(this,{"width":400,"height":400,"opacity":10});
})
})
}
div2.onmouseout = function() {
change(this,{"width":400,"height":300,"opacity":20},function() {
change(this,{"width":300,"height":300,"opacity":60},function() {
change(this,{"width":200,"height":200,"opacity":100});
})
})
}
function change(obj,target,callback) {
//首先清除上一个定时器
clearInterval(obj.timer);
//定义变量
var origin={};
var speed = 0;
var flag = true;
//遍历获取初始属性
for(attr in target) {
if( attr === "opacity" ) {
origin[attr] = Math.round(getStyle(obj,attr)*100);
} else {
origin[attr] = parseInt(getStyle(obj,attr));
}
}
//设置定时器
obj.timer = setInterval(function() {
//初始化标记true
flag = true;
//遍历目标值
for( attr in target) {
//计算速度
speed = (target[attr]-origin[attr])/10;
speed = speed>0?Math.ceil(speed):Math.floor(speed);
//改变初始数值
origin[attr] += speed;
if(attr === "opacity") {
obj.style.opacity = origin[attr]/100;
obj.style.filter = 'alpha(opacity='+origin[attr]+')';
} else {
obj.style[attr] = origin[attr] + "px";
}
//若有一个不等则将标记设为false
if(target[attr] != origin[attr]) {
flag = false;
}
}
console.log("定时器清除了没?");
//如果标记值为true清除定时器
if(flag) {
clearInterval(obj.timer);
//设置回调函数
if(callback) {
callback.call(obj);
}
}
},30);
}
//获取元素外联和内联样式
function getStyle(obj,attr) {
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj,false)[attr];
}
</script>
</body>
</html>