JavaScript 完善tween+drag

🌙
手机阅读
本文目录结构

html

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body,ul,li,img{margin: 0;padding: 0;-webkit-user-select: none;  }
        ul{list-style: none;width: 465px;height: 620px;position: absolute;top:0;left:-225px;padding:5px 0 0 5px;margin: 50px 50% 0;border: 2px solid orange;border-radius: 10px;}
        ul li{float: left;margin: 0 5px 5px 0;width: 150px;height: 150px;line-height: 150px;text-align: center;
            cursor: move;}
        ul li img{border: none;}
    </style>
</head>
<body>
<ul id="photolist">
    <li><img  alt="图片1" width="150" height="150" style="background: olive"/></li>
    <li><img  alt="图片2" width="150" height="150" style="background: orange"/></li>
    <li><img  alt="图片3" width="150" height="150" style="background: blueviolet"/></li>
    <li><img  alt="图片4" width="150" height="150" style="background: chocolate"/></li>
    <li><img  alt="图片5" width="150" height="150" style="background: darkblue"/></li>
    <li><img  alt="图片6" width="150" height="150" style="background: aquamarine"/></li>
    <li><img  alt="图片7" width="150" height="150" style="background: wheat"/></li>
    <li><img  alt="图片8" width="150" height="150" style="background: rosybrown"/></li>
    <li><img  alt="图片9" width="150" height="150" style="background: teal"/></li>
    <li><img  alt="图片10" width="150" height="150" style="background: yellowgreen"/></li>
    <li><img  alt="图片11" width="150" height="150" style="background: peru"/></li>
    <li><img  alt="图片12" width="150" height="150" style="background: indigo"/></li>
</ul>

</body>
</html>
<script src="tool.js"></script>
<script src="event.js"></script>
<script src="drag.js"></script>
<script src="tween.js"></script>
<script>
    var dom=new Tool();
    var oLis=document.getElementsByTagName("li");
    for(var i=oLis.length-1;i>=0;i--){
        var oLi=oLis[i];
        oLi.l=oLi.offsetLeft;
        oLi.t=oLi.offsetTop;
        oLi.style.left=oLi.l+"px";
        oLi.style.top=oLi.t+"px";
        oLi.style.position="absolute";
        oLi.style.margin=0;
        console.log("第"+i+"元素的:left,top值是:"+oLi.style.left+""+oLi.style.top+oLi.style.position)


        on(oLi,"mousedown",down);
        on(oLi,"selfDragStart",zIndexNum);
        on(oLi,"selfDragMove",getHitedEle);
        on(oLi,"selfDragEnd",changePosition);
/*        on(oLi,"selfDragEnd",function(){
            starMove(this,{left:this.l,top:this.t},600,8,restore)
            }
        )*/
    }

    var zIndex=1;
    function zIndexNum(){
        this.style.zIndex=++zIndex;
        this.style.border="2px solid red"
    }
    function restore(){
        this.style.border=""
    }

    function isHited(r,b){//判断是否判断
        if(r.offsetLeft+ r.offsetWidth< b.offsetLeft
        || r.offsetTop+ r.offsetHeight< b.offsetTop
        || r.offsetLeft> b.offsetLeft+ b.offsetWidth
        || r.offsetTop> b.offsetTop+ b.offsetHeight){
            return false;
        }else{
            return true;
        }
    }

    //*获取相交最近的li*//
    function getHitedEle(){
        this["aHitedEle"]=[];
        var subs= dom.getSiblings(this);
        for(var i=0;i<subs.length;i++){
            var oLi=subs[i];
            oLi.style.border="";
            if(isHited(this,oLi)){
                oLi.style.border="2px solid blue";
                this["aHitedEle"].push(oLi);
            }
        }
    }

    /*交换w位置*/
    function changePosition(){
        var ary= this["aHitedEle"];
        if(ary&&ary.length){
            var oMin={};
            for(var i=0;i< ary.length;i++){
                var oLi=ary[i];
                if(!oMin.ele){
                    oMin.min=Math.sqrt(Math.pow(this.offsetLeft-oLi.offsetLeft,2)+Math.pow(this.offsetTop-oLi.offsetTop,2));
                    oMin.ele=oLi;
                }else{
                    var distance=Math.sqrt(Math.pow(this.offsetLeft-oLi.offsetLeft,2)+Math.pow(this.offsetTop-oLi.offsetTop,2));
                    if(oMin.min>distance){
                        oMin.min=distance;
                        oMin.ele=oLi;
                    }
                }
            }
/*            //下面是交换位置
            oMin.ele.style.left=this.l+"px";
            oMin.ele.style.top=this.t+"px";
            this.style.left=oMin.ele.l+"px";
            this.style.top=oMin.ele.t+"px";
            *//*下面是更新交换后的位置*//*
            var objEle={l:this.l,t:this.t};
            this.l=oMin.ele.l;
            this.t=oMin.ele.t;
            oMin.ele.l=objEle.l;
            oMin.ele.t=objEle.t;*/

            /*下面是加动画效果的*/
            starMove(oMin.ele,{left:this.l,top:this.t},600,8,restore);
            starMove(this,{left:oMin.ele.l,top:oMin.ele.t},600,8,restore);
            //*下面是更新交换后的位置*//*
            var objEle={l:this.l,t:this.t};
            this.l=oMin.ele.l;
            this.t=oMin.ele.t;
            oMin.ele.l=objEle.l;
            oMin.ele.t=objEle.t;
            this["aHitedEle"]=null;
        }else{
            starMove(this,{left:this.l,top:this.t},600,8,restore)
        }

    }
</script>

event.js

/*on:是负责往数组里安排一个队列的,程序池*/
function on(ele,type,fn){
    /*约定type如果以self开头的字符串,就是自定义事件,如果不是的,就是系统的事件*/
    if(/^self/.test(type)){//判断是否是自定义事件,这里是自定义事件;
        if(!ele[type]){
            ele[type]=[];
        }
        var aryEvent=ele[type];
        for(var i=0;i<aryEvent.length;i++){//防止同一个方法被同事件绑定;
            if(aryEvent[i]==fn)return;
        }
        aryEvent.push(fn);
    }else{
        if(ele.addEventListener){
            ele.addEventListener(type,fn);
        }else{
            if(!ele["aEvent"+type]){
                ele["aEvent"+type]=[];
                //bind3(ele,type,run);//只会执行一次,防止重复绑定;上一次封装的事件库是用bind解决的
                ele.attachEvent("on"+type,function(){run.call(ele)})//放在这里,因为是在if里,所以是有条件执行的,而且这里是只执行一次;防止重复绑定;
            }
            var aryEvent=ele["aEvent"+type];
            for(var i=0;i<aryEvent.length;i++){//防止同一个方法被同事件绑定;
                if(aryEvent[i]==fn)return;
            }
            aryEvent.push(fn);
        }
    }
}

/*run:负责具体的执行,在这里把IE兼容性全部解决掉;run方法是由系统的事件来触发的,真正绑定的是run方法*/
function run(){//run方法只用在IE678,解决系统事件的兼容性问题;;
    var e=window.event;
    e.target= e.srcElement;
    e.pageX=(document.documentElement.scrollLeft||document.body.scrollLeft)+ e.clientX;
    e.pageY=(document.documentElement.scrollTop||document.body.scrollTop)+ e.clientY;
    e.stopPropagation=function(){e.cancelBubble=true;}//阻止事件传播;
    e.preventDefault=function(){e.returnValue=false;}//阻止事件默认行为;
    var a=this["aEvent"+e.type];
    for(var i=0;i< a.length;){
        /*下面是防止数组塌陷的*/
        if(typeof a[i]=="function"){//这个是和off呼应的,off里有为null的值;
            a[i].call(this,e);//以后给元素写的方法,约定好都要写一个e的参数,这样就不需要再解决IE兼容性了;
            i++;
        }else{
            a.splice(i,1);
        }
    }
}
/*fire是写在某一个方法最后,任何浏览器任何自定义事件都可以用*/
function fire(selfType,e){//第一个参数是自定义事件的类型;第二个事件是系统事件对象;
    var ary=this[selfType];
    if(ary){
        for(var i=0;i<ary.length;i++){
            if(typeof  ary[i]=="function"){
                ary[i].call(this,e);
                i++
            }else{
                ary.splice(i,1);
            }

        }
    }
}

function off(ele,type,fn){
    if(/^self/.test(type)){//自定义事件
        var ary=ele[type];
        if(ary){
            for (var i=0;i<ary.length;i++){
                if(ary[i]==fn){
                    ary[i]==null;
                    return;
                }
            }
        }
    }else{
        if(ele.removeEventListener){
            ele.removeEventListener(type,fn);
        }else {
            var aryEvent=ele["aEvent"+type];
            if(aryEvent&& aryEvent.length){
                for(var i=0;i<aryEvent.length;i++){
                    if(aryEvent[i]==fn){
                        aryEvent[i]=null;
                        return;
                    }
                }
            }
        }
    }

}

function bindThis(obj,fn){
    return function(e){fn.call(obj,e)}
}

drag.js

function down(e){//把down发布为一个事件;让别人能够约定的标识符;
    //识别符:"selfDragStart" ;
    this.x=this.offsetLeft;
    this.y=this.offsetTop;
    this.mouseX= e.pageX;
    this.mouseY= e.pageY;
    console.log("offsetLeft;offsetTop+e.pageX+e.pageY"+this.x+"==>"+this.y+"==>"+this.mouseX+"==>"+this.mouseY);
    if(this.setCapture){
        this.setCapture();
        on(this,"mousemove",move);
        on(this,"mouseup",up);
    }else{
        this._move=bindThis(this,move);
        this._up=bindThis(this,up);
        on(document,"mousemove",this._move);
        on(document,"mouseup",this._up);
    }
    e.preventDefault();//阻止默认行为,解决盒子因为加了图片,站住鼠标的BUG;
    fire.call(this,"selfDragStart",e);//这个是接口;
}
function move(e){
    this.style.left=this.x+ (e.pageX-this.mouseX)+"px";
    this.style.top=this.y+ (e.pageY-this.mouseY)+"px";
    fire.call(this,"selfDragMove",e);//这个是接口;
}
function up(e){
    if(this.releaseCapture){
        this.releaseCapture();
        off(this,"mousemove",move);
        off(this,"mouseup",up);
    }else{
        off(document,"mousemove",this._move);
        off(document,"mouseup",this._up);
    }
    fire.call(this,"selfDragEnd",e);//这个是接口;
}

tool.js

var Tool = function () {//构造函数模式;用的时候需要new一下;
    this.flag = "getElementsByClassName" in document;
    //getElementsByClassName 在IE678中是不存在的。用这个来判断是不是低版本的IE浏览器;
    //每次只需要判断this.flag是否存在就可以了;如果存在就是标准浏览器,如果不存在就是IE;
};
Tool.prototype = {//方法是定义在Tool的prototype上的;
    constructor: Tool,//重写prototype后,prototype的constructor已经不是原来的Tool了;需要手动给他强制写会到Tool上去;
    /*经常用到的函数*/
    getElementsByClassName: function (context,cName) {//获取元素的ClassName
        var context = context || document;
        var ary = [];
        if (this.flag) {
            return this.listToArray(context.getElementsByClassName(cName));
        }
        var allNode = context.getElementsByTagName("*");
        var reg = new RegExp("(?:^| +)" + cName + "(?: +|$)");
        for (var i = 0; i < allNode.length; i++) {
            var cur = allNode[i];
            if (reg.test(cur.className)) {
                ary.push(cur);
            }
        }
        return ary;
    },
    toJSON: function (jsonStr) {//将json字符串转化为json对象
        var jsonObj = null;
        try {
            jsonObj = JSON.parse(jsonStr);//如果支持 JSON.parse则直接使用 JSON.parse将JSON字符串转换为JSON对象。
        } catch (e) {
            jsonObj = eval("(" + jsonStr + ")");
        }
        return jsonObj;
    },
    isType: function (value,type) {//判断数据类型;
        var type = arguments[1] || "Object",
            reg = new RegExp("\\[object " + type + "\\]", "i");
        return reg.test({}.toString.call(value));//{}不可以是[],因为[]就不是Object.prototype,数组也有toString方法;
    },
    listToArray: function (likeAry) {//类数组转化为数组;
        var ary = [];
        if (this.flag) {
            ary = [].slice.call(likeAry, 0);
        } else {
            for (var i = 0; i < likeAry.length; i++) {
                ary.push(likeAry[i]);
            }
        }
        return ary;
    },

    /***下面是设置DOM***/
    getEleChildren: function (parent,tagName) {//获取指定节点名的元素节点们;第二个参数如果不传,则返回obj下的所有子元素节点;
        var allNode = parent.childNodes,
            ary = [],
            reg = new RegExp("^" + tagName + "$", "i");
        for (var i = 0; i < allNode.length; i++) {
            var cur = allNode[i];
            if (cur.nodeType === 1) {
                if (tagName) {//tahName不可能为0,false之类的数;所以可以用if直接判断传进来的参数;
                    if (reg.test(cur.nodeName)) {
                        ary.push(cur);
                    }
                    continue;
                }
                ary.push(cur);
            }
        }
        return ary;
    },
    getFirst: function (curEle) {//获取第一个元素节点;
        var children = this.getEleChildren(curEle);
        return children.length > 0 ? children[0] : null;
    },
    getLast: function (curEle) {//获取最后一个元素节点;
        var children = this.getEleChildren(curEle);
        return children.length > 0 ? children[children.length - 1] : null;
    },
    getPre: function (curEle) {//上一个哥哥节点;
        if (this.flag) {
            return curEle.previousElementSibling;
        }
        var pre = curEle.previousSibling;
        while (pre && pre.nodeType !== 1) {
            pre = pre.previousSibling;
        }
        return pre;
    },
    getPres: function (curEle) {//获得所有哥哥们;
        /*            var ary = [],
         attr = this.flag ? "previousElementSibling" : "previousSibling";
         var pre = curEle[attr];
         while (pre) {
         if (pre.nodeType === 1) {
         ary.unshift(pre);
         }
         pre = pre[attr];
         }
         return ary;*/
        var ary = [],
            next = this.getPre(curEle);
        while (next) {
            ary.unshift(next);
            next = this.getPre(next);
        }
        return ary;
    },
    getNext: function (curEle) {//下一个弟弟节点,第一个弟弟节点;
        if (this.flag) {
            return curEle.nextElementSibling;
        }
        var next = curEle.nextSibling;
        while (next && next.nodeType !== 1) {
            next = next.nextSibling;
        }
        return next;
    },
    getNexts: function (curEle) {//获取所有的弟弟们;
        var ary = [],
            next = this.getNext(curEle);
        while (next) {
            ary.push(next);
            next = this.getNext(next);
        }
        return ary;
    },
    getSibling: function (curEle) {//获取上一个哥哥和下一个弟弟;
        var ary = [],
            pre = this.getPre(curEle),
            next = this.getNext(curEle);
        pre ? ary.push(pre) : void 0;
        next ? ary.push(next) : void 0;
        return ary;
    },
    getSiblings: function (curEle) {//获取所有的兄弟们(除了自己)
        var pres = this.getPres(curEle),
            nexts = this.getNexts(curEle);
        return pres.concat(nexts);
    },
    getIndex: function (curEle) {//获取元素的索引值;
        return this.getPres(curEle).length;
    },
    insertAfter: function (newEle,oldEle) {//在目标元素oldEle后面插入新元素newEle;如果没有传指定元素,则直接添加在后面
        var next = this.getNext(oldEle),
            par = oldEle.parentNode;
        next ? par.insertBefore(newEle, next) : par.appendChild(newEle);
    },
    prependChild: function (parentEle,curEle) {//把一个元素节点添加为parentEle的第一个子节点;
        var first = this.getFirst(parentEle);//获取par中的第一个元素节点;
        first ? parentEle.insertBefore(curEle, first) : parentEle.appendChild(curEle);
    },
    innerHTML: function (curEle,str) {//获取元素的innerHTML;
        var str= str || "";
        if (!str) {
            return curEle.innerHTML;
        }
        curEle.innerHTML = str;
    },
    text:function (ele,str){//处理innerText和textContent的兼容性;传一个参数是获取;2个参数是设置;
        if(ele&&ele.nodeType&&ele.nodeType==1){
            if(str===undefined){//如果str没有传,那么方法是获取元素的文本内容;
                if(typeof ele.textContent=='string')
                    return ele.textContent;
                else
                    return ele.innerText;

            }else{//如果传了,就是添加文本内容
                if(str===null){
                    alert('text方法参数错误,str为null!');
                    return ;
                }else if(typeof str=='string'){
                    if(typeof ele.textContent=='string') {
                        ele.textContent += str;
                    }else{
                        ele.innerText+=str;
                    }
                }else{
                    alert('text方法的参数错误!')
                }
            }
        }else{
            alert('text方法的ele参数错误!')
        }
    },

    /***下面是设置CSS***/
    setCss:function (curEle,attr,value) {//设置CSS属性值和获取CSS;如果三个参数就是设置,2个参数就是获取;att是attribute的缩写;
        if(typeof value==="undefined"){//如果有第三个参数,就是设置Css;如果没有就是获取Css;
            var reg = /^(?:margin|padding|border|float|position|display|background|backgroundColor)$/;
            var value = this.flag ? window.getComputedStyle(curEle, null)[attr] : curEle.currentStyle[attr];
            return !reg.test(attr) ? parseFloat(value) : value;
        } else{
            switch (attr) {
                case "opacity":
                    curEle["style"][attr] = value;
                    curEle["style"]["filter"] = "alpha(opacity=" + (value * 100) + ")";
                    break;
                case "float":
                    curEle["style"].cssFloat = value;
                    curEle["style"].styleFloat = value;
                    break;
                case "backgroundColor":
                    curEle["style"][attr] = value;
                    break;
                case "zIndex":
                    curEle["style"][attr] = value;
                    break;
                default:
                    curEle["style"][attr] = !isNaN(value) ? value += "px" : value;
            }
        }
    },
    setGroupCss: function (curEle,cssObj) {//给元素设置一组属性;cssObj是一个对象类型;
        for (var key in cssObj) {
            this.setCss(curEle, key, cssObj[key]);
        }
    },
    offset: function (curEle) {//获取偏移量;
        var  par = curEle.offsetParent,
            left = curEle.offsetLeft,
            top = curEle.offsetTop;
        while (par) {
            left += par.offsetLeft;
            top += par.offsetTop;
            if (navigator.userAgent.indexOf("MSIE 8.0") <= -1) {
                left += par.clientLeft;
                top += par.clientTop;
            }
            par = par.offsetParent;
        }
        return {left: left, top: top};
    },
    hasClassName: function (curEle,cName) {//判断是否有某个className;
        var reg = new RegExp("(?:^| +)" + cName + "(?: +|$)");
        return reg.test(curEle.className);
    },
    addClassName: function (curEle,cName) {//增加某个className;
        if (!this.hasClassName(curEle,cName)) {
            curEle.className += (" " + cName);
        }
    },
    removeClassName: function (curEle,cName) {//移除类样式的方法;
        var reg = new RegExp("(?:^| +)" + cName + "(?: +|$)", "g");
        if (this.hasClassName(curEle,cName)) {
            curEle.className = curEle.className.replace(reg, " ");
        }
    }
};
~function () {//在DOM库上增加方法,同时不影响原来的方法;在类的原型上增加方法;
    var strPro = String.prototype,
        aryPro = Array.prototype,
        objPro = Object.prototype;
    aryPro.removeRepeat = function () {//数组去重;
        var obj = {};
        for (var i = 0; i < this.length; i++) {
            var cur = this[i];
            if (obj[cur] == cur) {
                this.splice(i, 1);
                i--;
                continue;
            }
            obj[cur] = cur;
        }
        obj = null;
        return this;
    };
    aryPro.forEachPro = function (fn,context) {//forEach兼容性处理;
        var context = context || window;
        if (this.forEach) {
            this.forEach(fn, context);
            return this;
        }
        for (var i = 0; i < this.length; i++) {
            fn.call(context, this[i], i, this);
        }
        return this;
    };
    objPro.myHasPubProperty = function (attr) {//是否为公有属性;
        return (attr in this) && !this.hasOwnProperty(attr);
    };
    strPro.myTrim = function () {//去除首尾空格;
        return this.replace(/(^\s*|\s*$)/g, "");
    };
    strPro.mySub = function (len,isD) {//是不是有效的
        var len = len || 10,
            isD = isD || false,
            str = "",
            n = 0;
        for (var i = 0; i < this.length; i++) {
            var s = this.charAt(i);
            /[\u4e00-\u9fa5]/.test(s) ? n += 2 : n++;
            if (n > len) {
                isD ? str += "..." : void 0;
                break;
            }
            str += s;
        }
        return str;
    };
    strPro.myFormatTime = function (format) {//时间格式化;
        var reg = /^(\d{4})(?:-|\/|\.|:)(\d{1,2})(?:-|\/|\.|:)(\d{1,2})(?:\s+)(\d{1,2})(?:-|\/|\.|:)(\d{1,2})(?:-|\/|\.|:)(\d{1,2})$/g,
            ary = [];
        this.replace(reg, function () {
            ary = ([].slice.call(arguments)).slice(1, 7);
        });
        var format = format || "{0}年{1}月{2}日 {3}:{4}:{5}";
        return format.replace(/{(\d+)}/g, function () {
            var val = ary[arguments[1]];
            return val.length === 1 ? "0" + val : val;
        });
    };
    strPro.myQueryURLParameter = function () {//是否是有效URL
        var reg = /([^?&=]+)=([^?&=]+)/g, obj = {};
        this.replace(reg, function () {
            obj[arguments[1]] = arguments[2];
        });
        return obj;
    }
}();

tween.js

function starMove(ele,jsonStr,duration,moveTypeNum,fnCallback){
    //多态:方法重载:JS如何实现方法重载。一个方法,可以有不同类型或个数的参数
    //方法重写:子类上的方法覆盖了父类上的方法
    var typeNum=moveType.jiansu4.starOut;
    if(typeof moveTypeNum =="number"){
        if(moveTypeNum===4){
            typeNum=moveType.jiansu4.starOut;
        }else if(moveTypeNum ===6){
            typeNum=moveType.jiansu4.starOut;
        }else if(moveTypeNum ===7 ){
            typeNum=moveType.jiansu7.starOut;
        }else if(moveTypeNum===8){
            typeNum=moveType.dabai.starOut;
        }else if(moveTypeNum===9){
            typeNum=moveType.xiaobai.starOut;
        }else if(moveTypeNum===10){
            typeNum=moveType.fantan.starOut;
        }
    }else if(typeof moveTypeNum=="object"){
        if(moveTypeNum instanceof Array){
            /*输入模式是["fantan","starInOut"]*/
            if(moveTypeNum.length==1){
                typeNum=moveType[moveTypeNum[0]];//moveTypeNum[0]是获取line方法
            }else if(moveTypeNum.length==2){
                typeNum=moveType[moveTypeNum[0]][moveTypeNum[1]]//moveType.jiansu1.starIn/out/inOut;
            }
        }
    }else if(typeof moveTypeNum=="function"){
        fnCallback=moveTypeNum;
    }

    var oBegin={};//不同方向的起始值;
    var oChange={};//不同方向的运动距离;
    var booleanNum=0;
    for(var attr in jsonStr){
        var begin=setCss(ele,attr);
        var target=jsonStr[attr];
        var change=target-begin;
        if(change){
            oBegin[attr]=begin;
            oChange[attr]=change;
            booleanNum++;
        }
    }
    if(booleanNum===0){
        if(typeof fnCallback=="function"){
            fnCallback.call(ele);
        }
        return;
    }else{
        var interval=13;
        var times=0;
        clearInterval(ele.timer);
        ele.timer=window.setInterval(move,interval);
        function move(){
            times+=interval;
            if(times>=duration){
                clearInterval(ele.timer);
                ele.timer=null;
                for(var attr in jsonStr){
                    setCss(ele,attr,jsonStr[attr]);
                }
                if(typeof fnCallback=="function"){
                    fnCallback.call(ele);
                }
            }else{
                for(var attr in oChange){
                    //动画效果在这里
                    var targetNumber=typeNum(times,oBegin[attr],oChange[attr],duration);
                    setCss(ele,attr,targetNumber);
                }
            }
        }
    }
};


//回调方法;
function toGreen(){
    setCss(this,"backgroundColor","green");
};

/*setCss*/
function setCss(curEle,attr,value) {//设置CSS属性值和获取CSS;如果三个参数就是设置,2个参数就是获取;att是attribute的缩写;
    if(typeof value==="undefined"){//如果有第三个参数,就是设置Css;如果没有就是获取Css;
        var reg = /^(?:margin|padding|border|float|position|display|background|backgroundColor)$/;
        var flag="getElementsByClassName" in document;
        var value = flag ? window.getComputedStyle(curEle, null)[attr] : curEle.currentStyle[attr];
        return !reg.test(attr) ? parseFloat(value) : value;
    } else{
        switch (attr) {
            case "opacity":
                curEle["style"][attr] = value;
                curEle["style"]["filter"] = "alpha(opacity=" + (value * 100) + ")";
                break;
            case "float":
                curEle["style"].cssFloat = value;
                curEle["style"].styleFloat = value;
                break;
            case "backgroundColor":
                curEle["style"][attr] = value;
                break;
            case "zIndex":
                curEle["style"][attr] = value;
                break;
            default:
                curEle["style"][attr] = !isNaN(value) ? value += "px" : value;
        }
    }
};

/*数学计算*/
var moveType = {
    /*直线运动*///当前时间*变化量/持续时间+初始值
    line: function(t,b,c,d){ return c*t/d + b; },

    /*减速中最长用的是4、6、7*/
    jiansu1: {//二次方的缓动(t^2);
        starIn: function(t,b,c,d){
            return c*(t/=d)*t + b;
        },
        starOut: function(t,b,c,d){
            return -c *(t/=d)*(t-2) + b;
        },
        starInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t + b;
            return -c/2 * ((--t)*(t-2) - 1) + b;
        }
    },
    jiansu2: {//三次方的缓动(t^3)
        starIn: function(t,b,c,d){
            return c*(t/=d)*t*t + b;
        },
        starOut: function(t,b,c,d){
            return c*((t=t/d-1)*t*t + 1) + b;
        },
        starInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t*t + b;
            return c/2*((t-=2)*t*t + 2) + b;
        }
    },
    jiansu3: {//四次方的缓动(t^4);
        starIn: function(t,b,c,d){
            return c*(t/=d)*t*t*t + b;
        },
        starOut: function(t,b,c,d){
            return -c * ((t=t/d-1)*t*t*t - 1) + b;
        },
        starInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t*t*t + b;
            return -c/2 * ((t-=2)*t*t*t - 2) + b;
        }
    },
    jiansu4: {//5次方的缓动(t^5);
        starIn: function(t,b,c,d){
            return c*(t/=d)*t*t*t*t + b;
        },
        starOut: function(t,b,c,d){
            return c*((t=t/d-1)*t*t*t*t + 1) + b;
        },
        starInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b;
            return c/2*((t-=2)*t*t*t*t + 2) + b;
        }
    },
    jiansu5: {//正弦曲线的缓动(sin(t))
        starIn: function(t,b,c,d){
            return -c * Math.cos(t/d * (Math.PI/2)) + c + b;
        },
        starOut: function(t,b,c,d){
            return c * Math.sin(t/d * (Math.PI/2)) + b;
        },
        starInOut: function(t,b,c,d){
            return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b;
        }
    },
    jiansu6: {//指数曲线的缓动(2^t);
        starIn: function(t,b,c,d){
            return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b;
        },
        starOut: function(t,b,c,d){
            return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b;
        },
        starInOut: function(t,b,c,d){
            if (t==0) return b;
            if (t==d) return b+c;
            if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b;
            return c/2 * (-Math.pow(2, -10 * --t) + 2) + b;
        }
    },
    jiansu7: {//圆形曲线的缓动(sqrt(1-t^2));
        starIn: function(t,b,c,d){
            return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b;
        },
        starOut: function(t,b,c,d){
            return c * Math.sqrt(1 - (t=t/d-1)*t) + b;
        },
        starInOut: function(t,b,c,d){
            if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b;
            return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b;
        }
    },
    /*大摆动的效果,非常绚丽;比xiaobai好*/
    dabai: {//指数衰减的正弦曲线缓动;
        starIn: function(t,b,c,d,a,p){
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
            if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
        },
        starOut: function(t,b,c,d,a,p){
            if (t==0) return b;  if ((t/=d)==1) return b+c;  if (!p) p=d*.3;
            if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            return (a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b);
        },
        starInOut: function(t,b,c,d,a,p){
            if (t==0) return b;  if ((t/=d/2)==2) return b+c;  if (!p) p=d*(.3*1.5);
            if (!a || a < Math.abs(c)) { a=c; var s=p/4; }
            else var s = p/(2*Math.PI) * Math.asin (c/a);
            if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b;
            return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b;
        }
    },
    xiaobai: {//超过范围的三次方缓动((s+1)*t^3 - s*t^2);
        starIn: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158;
            return c*(t/=d)*t*((s+1)*t - s) + b;
        },
        starOut: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158;
            return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b;
        },
        starInOut: function(t,b,c,d,s){
            if (s == undefined) s = 1.70158;
            if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b;
            return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b;
        }
    },
    fantan: {//指数衰减的反弹缓动。
        starIn: function(t,b,c,d){
            return c - moveType.fantan.starOut(d-t, 0, c, d) + b;
        },
        starOut: function(t,b,c,d){
            if ((t/=d) < (1/2.75)) {
                return c*(7.5625*t*t) + b;
            } else if (t < (2/2.75)) {
                return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b;
            } else if (t < (2.5/2.75)) {
                return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b;
            } else {
                return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b;
            }
        },
        starInOut: function(t,b,c,d){
            if (t < d/2) return moveType.fantan.starIn(t*2, 0, c, d) * .5 + b;
            else return moveType.fantan.starOut(t*2-d, 0, c, d) * .5 + c*.5 + b;
        }
    }
};

AXIHE / 精选资源

浏览全部教程

面试题

学习网站

前端培训
自己甄别

前端书籍

关于朱安邦

我叫 朱安邦,阿西河的站长,在杭州。

以前是一名平面设计师,后来开始接接触前端开发,主要研究前端技术中的JS方向。

业余时间我喜欢分享和交流自己的技术,欢迎大家关注我的 Bilibili

关注我: Github / 知乎

目前重心已经放在研究区块链上面了

我叫朱安邦,阿西河的站长

目前在杭州从事区块链周边的开发工作,机械专业,以前从事平面设计工作。

2014年底脱产在老家自学6个月的前端技术,自学期间几乎从未出过家门,最终找到了满意的前端工作。更多>