关闭

多物体运动

标签: javascript
98人阅读 评论(0) 收藏 举报
分类:

<!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.onload=function(){

var ali=document.getElementsByTagName('li');
for(var i=0;i<ali.length;i++){
ali[i].timer=null;
ali[i].onmouseover=function(){
move(this,400);
}
ali[i].onmouseout=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.onload=function(){

var ali=document.getElementsByTagName('li');
for(var i=0;i<ali.length;i++){
ali[i].timer=null;
ali[i].onmouseover=function(){
move(this,400);
}
ali[i].onmouseout=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>

0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:4356次
    • 积分:249
    • 等级:
    • 排名:千里之外
    • 原创:20篇
    • 转载:5篇
    • 译文:0篇
    • 评论:0条
    文章分类