rplus.github.io icon indicating copy to clipboard operation
rplus.github.io copied to clipboard

[POST] JS vendor prefix detection

Open Rplus opened this issue 10 years ago • 1 comments

今天翻舊文看到一個用 Array.some 來處理各瀏覽器 vendor prefix 的方法

下面是原本的寫法 利用的是 some 只要一遇到 true 值 return 就會中止(不必要的) loop

// source: http://stackoverflow.com/a/24107550/5940513
var matchesFn;

// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function(fn) {
    if (typeof document.body[fn] == 'function') {
        matchesFn = fn;
        return true;
    }
    return false;
});

不過我覺得如果不想管它是真是假的話,程式會少一些~

var matchesFn = null;

// find vendor prefix
['matches','webkitMatchesSelector','mozMatchesSelector','msMatchesSelector','oMatchesSelector'].some(function (fn) {
    if (typeof document.body[fn] === 'function') {
        matchesFn = fn;
    }
    return matchesFn;
});

或是更殘暴點,直接把判斷 return 回去

var matchesFn = null;
var matchesArray = ['aamatches', 'webkitMatchesSelector', 'mozMatchesSelector', 'msMatchesSelector', 'oMatchesSelector'];
// find vendor prefix
matchesArray.some((fn) => matchesFn = (typeof document.body[fn] === 'function') && fn);

這技巧可以用在相關的 feature detection 上 ex: https://gist.github.com/Rplus/16117dc7b7567ba27162 如果是用 [].some 的話,就不用多寫那個 for loop 跟 控制 break 的時間點了

不過這一例的 for loop 是因為需要另外處理字串前綴~

Rplus avatar Feb 22 '16 09:02 Rplus

這大小寫怎麼差這麼多........

http://www.sitepoint.com/css3-animation-javascript-event-handlers/ Browser Compatibility

W3C standard Firefox webkit Opera IE10
animationstart animationstart webkitAnimationStart oanimationstart MSAnimationStart
animationiteration animationiteration webkitAnimationIteration oanimationiteration MSAnimationIteration
animationend animationend webkitAnimationEnd oanimationend MSAnimationEnd
var pfx = ["webkit", "moz", "MS", "o", ""];
function PrefixedEvent(element, type, callback) {
    for (var p = 0; p < pfx.length; p++) {
        if (!pfx[p]) type = type.toLowerCase();
        element.addEventListener(pfx[p]+type, callback, false);
    }
}

Rplus avatar Feb 22 '16 13:02 Rplus