js让页面动起来 互动版

在线工具推荐: Three.js AI纹理开发包 - YOLO合成数据生成器 - GLTF/GLB在线编辑 - 3D模型格式在线转换 - 可编程3D场景编辑器

多物体运动

实现思路:

对多个物体进行绑定事件,达到控制多个元素同时运动效果

效果

logo运动


获取所有的li元素,用循环的方式给所有li元素绑定事件

注意:
我们为获取到的每个li元素对象添加了timer属性,大家应该还记得我在前面课程中提到的关于timer的问题.若是用一个timer变量,后果是什么呢?
timer的值将是后一次onmouseover或者onmouseout触发的定时器的ID,而无法清除前面的定时器。


window.onload=function(){
     var Larr=document.getElementsByTagName('li');
     for (var i = 0;i<Larr.length; i++) {
        Larr[i].timer=null;
        Larr[i].onmouseover=function(){
            startMove(this,300);
         };
         Larr[i].onmouseout=function(){
            startMove(this,200);
         }
     };

函数的编写

function startMove(_this,Target){
  clearInterval(_this.timer);
  _this.timer=setInterval(function(){
    var speed=(Target-_this.offsetWidth)/5;
    speed=speed>0?Math.ceil(speed):Math.floor(speed);
    if(_this.offsetWidth===Target){
        clearInterval(_this.timer);
    }
    else{
        _this.style.width=_this.offsetWidth+speed+'px';
    }
  },30);
}
为右边的Larr加入timer属性