deerforest的博客

前端笔记

多物体运动

<!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>

阅读更多
版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/deeerforest/article/details/51565095
文章标签: javascript
个人分类: javascript
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

不良信息举报

多物体运动

最多只允许输入30个字

加入CSDN,享受更精准的内容推荐,与500万程序员共同成长!
关闭
关闭