我用DOM2級綁定多個事件,為什么要把定時器取消才能執(zhí)行?
<!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:yellow;
margin-bottom:20px;
border:4px?solid?#000;
filter:alpha(opacity=30);
opacity:0.3;
}
</style>
<script?src="move.js"></script>
</head>
<body>
<ul>
<li?id="li1"></li>
</ul>
<script?type="text/javascript">
var?Li=document.getElementById('li1');
Li.addEventListener('mouseover',function(){startMove(Li,'width',400);},false);
Li.addEventListener('mouseover',function(){startMove(Li,'height',200);},false);
Li.addEventListener('mouseover',function(){startMove(Li,'opacity',100);},false);
</script>
</body>
</html>接下來是引入的js部分
function?getStyle(obj,attr){//傳入兩個參數(shù):對象和屬性
if?(obj.currentStyle)?{??//currentStyle針對ie瀏覽器
return?obj.currentStyle[attr];
}?else?{???//getComputerStyle針對firefox瀏覽器
return?getComputedStyle(obj,false)[attr];
}
}
//?var?timer=null;
function?startMove(obj,attr,iTarget,fn){
//?clearInterval(obj.timer);
obj.timer=setInterval(function(){
//1、取當前的值
var?icur=0;
if?(attr=='opacity')?{
icur=Math.round(parseFloat(getStyle(obj,attr))*100);
//*100是為了和17行代碼中的透明度對應
}?else?{
icur=parseInt(getStyle(obj,attr));
}
//2、計算速度
var?speed=(iTarget-icur)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//3、檢測停止
if?(icur==iTarget)?{
clearInterval(obj.timer);
if?(fn)?{
fn();
}
}?else?{
if?(attr=='opacity')?{
obj.style.filter='alpha(opacity='+(icur+speed)+')';//針對ie瀏覽器
obj.style.opacity=(icur+speed)/100;//針對firefox和chrome瀏覽器的
}?else?{
//?obj.style.width=icur+speed+'px';
obj.style[attr]=icur+speed+'px';
}
}
},30)
}
2016-09-08
分別給li添加mouseover事件后,后一個li里面的startMove()里面的clearInterval()會清除上一個li的startMove()函數(shù)里的定時器,所以就只有最后一個有效果了
2016-09-01
關于js部分第10行,清楚定時器,為什么要注釋掉才有效果,如果不注釋掉,只有透明度的變化,想不明白