響應式頁面越來越流行,所以現在很多交互都需要通過判斷瀏覽器是否支持某種事件,再去監聽不同的事件實現的,
比如 : touchstart、touchmove、touchend 與 mousedown、mousemove、mouseup
移動端我們就用touch類的事件 代替 mouse 類的事件,以下我們一起來探討一下如何準確地獲取各類事件
爲確保準確性,沒有比生成一個空的元素,做特性檢測更靠譜的了
1.使用 in 運算符,檢測對象中是否存在事件
var div = document.createElement('div'),
//是否支持觸摸事件
supportTouch = 'ontouchstart' in div,
//是否支持方向轉換事件
supportOtc = 'onorientationchange' in window;
2.通過元素的style屬性匹配出事件
此方法適合於獲取一些跟css相關的事件,如animation、transition
以animationend爲例,我們知道根據不同的瀏覽器會有以下幾種
‘animationend’、’webkitAnimationEnd’、’oAnimationEnd’、’MSAnimationEnd’、’mozAnimationEnd’
這類事件我建議用元素的style屬性獲取,爲啥呢?
按照以前的話,個個瀏覽器都有自己的一套,
比如通過判斷當前爲chrome、safari用webkitAnimationEnd,
firefox用mozAnimationEnd…
但現在各個瀏覽器都向規範靠攏了。
通過方法一輪詢?
我們測試一下
var i,
re = /^on[a-zA-z]*?[aA]nimation/
for ( i in window ) {
if ( re.test(i) ) {
document.write( i + '<br />')
}
}
chrome下面可以找到 ‘onwebkitanimationend’ 的,
firefox 36.0.4 壓根沒找到相關的
firefox不支持 animationend 事件嗎?用jquery測試一下
$(window).on('animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd mozAnimationEnd',function(e) {
console.log(e.type);
//firefox 36.0.4打印的是 animationend
});
根據這樣我們可以肯定新版的firefox已經向標準靠攏了
而通過style
var i,
re_forStyle = /animation/i;
for ( i in style ) {
if ( re_forStyle.test(i) ) {
document.write( i + '<br />')
}
}
我們可以獲知
chrome[41.0.2272.118]、opera[28.0.1750.51]、safari for window[5.1.7] 用的是 webkitAnimation
firefox 36.0.4 animation及MozAnimation都有
ie[11] animation及msAnimation都有
…
真夠亂的
這樣我們就可以通過這個hash表
{
animation : 'animationend',
WebkitAnimation : 'webkitAnimationEnd',
OAnimation : 'oAnimationEnd', //兼容舊版本opera
msAnimation : 'MSAnimationEnd',
MozAnimation : 'mozAnimationEnd' //兼容舊版本firefox
}
對應取值了,代碼如下
var div = document.createElement('div'),
style = div.style,
animationNames = ['animation','WebkitAnimation','OAnimation','msAnimation','MozAnimation'],
/**
* 通過style對象獲取正確的 animation 名稱
* @return { String || Boolean } animation 名稱
*/
animationName = (function(){
var i = 0,
len = animationNames.length,
name,
u;
for ( ; i < len ; i++) {
name = animationNames[i];
if ( style[name] !== u ) return name;
}
return false;
})(),
//真實的animationend
aniEndName = {
animation : 'animationend',
WebkitAnimation : 'webkitAnimationEnd',
OAnimation : 'oAnimationEnd',
msAnimation : 'MSAnimationEnd',
MozAnimation : 'mozAnimationEnd'
}[ animationName ];
console.log(animationName)
div = style = animationNames = animationName = null;
aniEndName && window.addEventListener(aniEndName, function(e) {
console.log(e.target);
})
另外,可以通過此方法檢測 transform 樣式名稱
var div = document.createElement('div'),
style = div.style,
transforms = [ 'transform', 'webkitTransform', 'MozTransform', 'msTransform', 'OTransform' ],
tfName = (function(){
var i = 0,
len = transforms.length,
name,
u;
for ( ; i < len; i++ ) {
name = transforms[i];
if ( style[ name ] !== u ) return name;
}
return false;
})();
transforms = style = div = null;
總結
1.沒涉及到css的使用 in 運算符,檢測對象中是否存在事件;
2.涉及到css的可以通過元素的style屬性匹配出事件。