javascript动画效果之多物体缓冲运动
这个是通过一个for循环控制的三个li标签,被鼠标触发则会有一个宽度增加和减少的事件
html和css同样写在一起方便察看,这里就是简单的布局,重点在js
1 <!DOCTYPE html> 2 <html> 3 4 <head> 5 <meta charset="UTF-8"> 6 <title>Document</title> 7 <style type="text/css"> 8 * { 9 margin: 0; 10 padding: 0; 11 font-size: 12px; 12 } 13 14 div { 15 margin: 10px; 16 height: 360px; 17 width: 200px; 18 } 19 20 ul { 21 list-style: none; 22 } 23 24 ul li { 25 width: 200px; 26 height: 100px; 27 background: blue; 28 margin-bottom: 20px; 29 cursor: pointer; 30 } 31 </style> 32 </head> 33 34 <body> 35 <div> 36 <ul id="ali"> 37 <li></li> 38 <li></li> 39 <li></li> 40 </ul> 41 </div> 42 43 44 </body> 45 46 </html>
js部分就是通过for循环给每个li都绑定事件,同时为了避免冲突,每个li都需要一个单独的定时器
<script type="text/javascript">
function $(id) {
return typeof id === "string" ? document.getElementById(id) : id;
}
window.onload = function() {
//自定义变量aLi为li标签的集合
var aLi = $("ali").getElementsByTagName("li");
//自定义变量
var speed = 0;
//通过for循环触发三个鼠标移动事件
for (var i = 0; i < aLi.length; i++) {
//为每个li都设置一个定时器,防止冲突
aLi[i].timer = null;
//鼠标移动进入,绑定事件
aLi[i].onmouseenter = function() {
//调用自定义函数,并传参
start(this, 400);
}
//鼠标移动离开,绑定事件
aLi[i].onmouseleave = function() {
//调用同一个自定义函数,并传参
start(this, 200);
}
}
//自定义函数,自定义参数
function start(one, two) {
//清楚定时器,因为一个li只有一个定时器能执行
clearInterval(one.timer);
//one对应上面aLi[i],所以one.timer就是aLi[i].timer
one.timer = setInterval(function() {
//speed通过(two-one.offsetWidth)也就是(400-200)
//console.log(speed);
speed = (two - one.offsetWidth) / 10;
//判断是增加width还是减少
speed = speed > 0 ? Math.ceil(speed) : Math.floor(speed);
if (one.offsetWidth == two) {
//当为400或者200时候,清除定时器
clearInterval(one.timer);
} else {
//通过speed自增减
one.style.width = one.offsetWidth + speed + 'px';
}
}, 30);
}
}
</script>
个人学习随笔,不一定原创,不定时更新
[gitHub]: https://github.com/MicahZJ
[博客]: https://micahzj.github.io/MicahZJ.github.io/
[掘金]: https://juejin.im/user/5c1355ebe51d4521030cfe84/posts/
有关问题,或者想和本人讨论
欢迎通过本人QQ872219020联系
或者在github上提issues,虽然我不一定会去看o
[gitHub]: https://github.com/MicahZJ
[博客]: https://micahzj.github.io/MicahZJ.github.io/
[掘金]: https://juejin.im/user/5c1355ebe51d4521030cfe84/posts/
有关问题,或者想和本人讨论
欢迎通过本人QQ872219020联系
或者在github上提issues,虽然我不一定会去看o

浙公网安备 33010602011771号