本人也是菜鸟一枚,从网上搜索了很久,封装备注了一套运动框架,加强大家对此的理解,希望多多提议。

    getId:function(elemId){
        return document.getElementById(elemId);
    },
    getStyle:function(obj,attr){
        return obj.currentStyle?obj.currentStyle[attr]:getComputedStyle(obj, false)[attr];
    },
    startMove:function(obj,json,fnEnd){
        /*
            obj 代表需要运动的对象
            json 需要运动的属性的集合 例如{'width':100,'height':100}
            fnEnd 运动结束时的函数
        */
        var _this = this;
        clearInterval(obj.timer); //若物体有运动,先清除计时器

        obj.timer = setInterval(function(){
            var eStop = true;  //表示物体运动
            for(var attr in json){
                var start = 0;
                if(attr == 'opacity'){ //如果是透明度的属性
                    start = Math.round(Math.floor(_this.getStyle(obj,attr)*100));
                }else{
                    start = parseInt(_this.getStyle(obj,attr));
                }
                //如果
                if(start != json[attr]){
                    eStop = false;
                }

                //设置速度的值
                var speed = (json[attr] - start)/6
                //如果大于0就向上取整,否则就向下取整;
                speed > 0 ? Math.ceil(speed) : Math.floor(speed);
                //如果透明度的变化
                if(attr == 'opacity'){
                    obj.style.filter = 'alpha(opacity:'+ (start + speed) +')';//设置IE
                    obj.style.opacity = (start+ speed)/100;
                }else{
                    //此时就是除了透明度的其他属性
                    obj.style[attr] = start + speed + 'px';
                }
            }
            //如果eStop == true 时 完成运动 到达目标点 清除计时器
            if(eStop){
                clearInterval(obj.timer);
                if(fnEnd) fnEnd();
            }
        },30)

    }

上面是我封装的三个方法:

调用如下

    elemMouse:function(){
        var _this = this;
        var conPhone = this.getId('conPhone');
        this.addEvent(conPhone,'mouseover',function(){
            _this.startMove(conPhone,{'width':500,'height':500,},function(){
                alert('运动结束')
            })
        })
        this.addEvent(conPhone,'mouseout',function(){
            _this.startMove(conPhone,{'width':300,'height':50},function(){
                alert('运动结束')
            })
        })
    }

 

posted on 2016-12-08 18:31  Mr、react  阅读(235)  评论(0编辑  收藏  举报