transitionEnd和animationEnd的一個臨時解決方案

看風景就發表於2018-07-05

transtionEnd需要新增字首,並且存在多次觸發問題,animationEnd也需要新增字首,下面是一個臨時性解決方案,解決了部分問題,完美方案探索中

(function(){
    var body=document.body || document.documentElement,
        style=body.style;

    var vendorPrefix=(function(){
        var i=0, vendor=["Moz", "Webkit", "Khtml", "O", "ms"];
        transition=transition.charAt(0).toUpperCase() + transition.substr(1);   
        while (i < vendor.length) {
            if (typeof style[vendor[i] + transition] === "string") {
                return vendor[i];
            }
            i++;
        }
        return false;
    })();

    var    transitionEnd=(function(){
        var transEndEventNames = {
            WebkitTransition : 'webkitTransitionEnd',
            MozTransition    : 'transitionend',
            OTransition      : 'oTransitionEnd otransitionend',
            transition       : 'transitionend'
        }
        for(var name in transEndEventNames){
            if(typeof style[name] === "string"){
                return transEndEventNames[name]
            }
        }
    })();

    var animationEnd=(function(){
        if(vendorPrefix=="Webkit"){
            return "webkitAnimationEnd";
        }else{
            return "animationend";
        }
    }());

    //解決多次觸發問題,transitionEnd在多個屬性變化時候會觸發多次,子元素也會冒泡,造成父元素事件觸發    
    //解決不觸發問題,duration後檢查是否觸發,未觸發則強制觸發
    function addTransitionEndOnce(ele,fn,duration){    
        var called = false;
        var callback = function(){
            if (!called){
                fn();
                called = true;
            }
        };
        var callbackEnd = function(){
            callback();
            setTimeout(callback, duration);
            ele.removeEventListener(transitionEnd, callbackEnd);
        }
        ele.addEventListener(transitionEnd, callbackEnd);
    }

    window.vendorPrefix = vendorPrefix;
    window.transitionEnd = transitionEnd;
    //animationEnd只加字首,自行註冊事件即可,不存在多次問題
    window.animationEnd = animationEnd;
    window.addTransitionEnd = addTransitionEnd;
});

 

相關文章