2013-05-08 49 views
5

我有一些JavaScript會觸發一些會導致CSS轉換的樣式更改。如何在沒有瀏覽器嗅探的情況下支持transitionend?

我應該如何掛鉤在轉換完成後執行的回調。顯然,在舊版瀏覽器中,它會立即轉換,但這些也不會識別轉換結束事件。

什麼是做這個短結合不同的事件,如果($ .browser.msie & & $ .browser.version < = 9)的最好辦法 - 我的理解是不好的做法。

下面是一個簡單的例子來說明我的觀點:

HTML

<div>test</div> 

CSS

div { 
    border: 1px solid black; 
    transition: width 2s; 
    width: 5px 
} 

.test { 
    width: 100px; 
} 

JS

$(function(){ 
    $(document).on('transitionend', function(){ 
     alert('transition complete'); 
    }); 
    $('div').addClass('test'); 
}); 

直播JS提琴:http://jsfiddle.net/vsDrH/1/

在舊版瀏覽器中使此事件有效的最佳方式是什麼?

感謝您的任何幫助。

回答

5

您可以檢查CSS屬性在這樣的瀏覽器支持:

http://jsfiddle.net/vsDrH/3/

function isSupported(property) { 
    return property in document.body.style; 
} 

$(function(){ 
    $(document).on('transitionend', function(){ 
     alert('transition complete'); 
    }); 
    $('div').addClass('test'); 

    if(!isSupported('transition')) { 
     $(document).trigger('transitionend'); 
    } 
}); 
+2

這不會工作! transitionend是一個事件,不是樣式對象的屬性,所以即使瀏覽器支持該事件,isSupported函數也將返回false。 – brennanyoung 2014-02-20 21:14:26

3

你可以看看的jQuery Transit的源代碼。這是非常好的書面和自我解釋。

的原則有很簡單:

  1. 你得到的過渡屬性的名稱,嗅出了瀏覽器的渲染引擎;
  2. 下一步,我們有不同的瀏覽器所有事件名稱,從中獲取特定的瀏覽器
  3. 在任何其他情況下,事件的名稱列表,如果沒有transitionend屬性存在,你應該考慮實施setTimeout計時器,以獲得最佳的跨瀏覽器效率。

的JavaScript(直接:jQuery Transit Source Code

// Helper function to get the proper vendor property name. 
// (`transition` => `WebkitTransition`) 

// (1) 

function getVendorPropertyName(prop) { 
    // Handle unprefixed versions (FF16+, for example) 
    if (prop in div.style) return prop; 

    var prefixes = ['Moz', 'Webkit', 'O', 'ms']; 
    var prop_ = prop.charAt(0).toUpperCase() + prop.substr(1); 

    if (prop in div.style) { return prop; } 

    for (var i=0; i<prefixes.length; ++i) { 
     var vendorProp = prefixes[i] + prop_; 
     if (vendorProp in div.style) { return vendorProp; } 
    } 
} 

// (2) 

var eventNames = { 
    'transition':  'transitionEnd', 
    'MozTransition': 'transitionend', 
    'OTransition':  'oTransitionEnd', 
    'WebkitTransition': 'webkitTransitionEnd', 
    'msTransition':  'MSTransitionEnd' 
}; 

var eventName = eventNames[getVendorPropertyName('transition')] || null 

// (3) 

if (eventName) { 
    // Use the 'transitionend' event if it's available. 
    bound = true; 
    element.bind(eventName, cb); 
} else { 
    // Fallback to timers if the 'transitionend' event isn't supported. 
    window.setTimeout(cb, delay); 
} 

這樣做,你將100%確保您的transitionEnd事件將觸發

+1

'transition':'transitionend',(或者它不適用於Chrome) – Eugene 2017-11-02 10:25:35

相關問題