之前初学的时候,都是用offset属性来设置,发现如果在没有边框的样式下,没有出现问题,但是如果加入了边框,就会出现与目标值不一样的情况,查阅了资料后发现了这个getStyle方法,currentStyle是针对IE的,getComputedStyle是针对火狐的,我也不太了解这种封装好的方法,不过效果不错。
<!DOCTYPE html>
<html><head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
ul,li{list-style: none;}
ul li{
width: 200px;
height: 100px;
background: yellow;
margin-bottom: 20px;
border: 2px solid black;
}
</style>
<script type="text/javascript">
window.onload = function(){
var ali = document.getElementsByTagName('li');
for(var i = 0;i<ali.length;i++){
ali[i].timer = null;
ali[i].onmouseover = function(){
startmove(this,400);
}
ali[i].onmouseout = function(){
startmove(this,200);
}
}
}
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj,false)[attr];
}
}
// var timer = null;
function startmove(obj,iTarget){
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = (iTarget - parseInt(getStyle(obj,'width')))/8;
speed = speed > 0?Math.ceil(speed):Math.floor(speed);
if(parseInt(getStyle(obj,'width')) == iTarget){
clearInterval(obj.timer);
}else{
obj.style.width = parseInt(getStyle(obj,'width')) + speed + 'px';
}
},30)
}
</script>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>