<!DOCTYPE html>
<head><title>untitled</title>
<meta charset="utf-8">
<style>
*{margin:0;padding:0;}
ul li{list-style:none;}
ul li{
width:200px;
height:100px;
background-color:#CD3278;
margin-bottom:20px;
}
</style>
<script>
window.οnlοad=function(){
var ali=document.getElementsByTagName('li');
for(var i=0;i<ali.length;i++){
ali[i].timer=null;
ali[i].οnmοuseοver=function(){
move(this,400);
}
ali[i].οnmοuseοut=function(){
move(this,200);
}
}
}
function move(obj,target){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var speed=(target-obj.offsetWidth)/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(obj.offsetWidth==target){
clearInterval(timer);
}
else{
obj.style.width=obj.offsetWidth+speed+'px';
}
},20)
}
</script>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>
给块添加border后,效果将不能实现,此时应封装函数来获取样式,如下所示:
<!DOCTYPE html>
<head>
<title>untitled</title>
<meta charset="utf-8">
<style>
*{margin:0;padding:0;}
ul li{list-style:none;}
ul li{
width:200px;
height:100px;
background-color:#CD3278;
margin-bottom:20px;
}
</style>
<script>
window.οnlοad=function(){
var ali=document.getElementsByTagName('li');
for(var i=0;i<ali.length;i++){
ali[i].timer=null;
ali[i].οnmοuseοver=function(){
move(this,400);
}
ali[i].οnmοuseοut=function(){
move(this,200);
}
}
}
function move(obj,target){
clearInterval(obj.timer);
obj.timer=setInterval(function(){
var speed=(target-parseInt(getStyle(obj,'width')))/8;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
if(parseInt(getStyle(obj,'width'))==target){
clearInterval(timer);
}
else{
obj.style.width=parseInt(getStyle(obj,'width'))+speed+'px';
}
},20)
}
function getStyle(obj, attr){
if(obj.currentStyle){
return obj.currentStyle[attr];
}
else{
return getComputedStyle(obj, false)[attr];
}
}
</script>
</head>
<body>
<ul>
<li></li>
<li></li>
<li></li>
<li></li>
</ul>
</body>
</html>