在WEB前端開發中,處理各瀏覽器差異的問題是一個重要的部分。
不同瀏覽器的內核及解析方式不同,對對象名和方法名的定義不同,導致寫出來的代碼不能得到我們想要的效果。所以在開發的時候需要解決這些問題。瀏覽器差異體現在很多方面,本文主要對事件處理作出理解。
下面介紹處理瀏覽器差異的通解和舉例說明一些事件處理機制的對象和方法處理。
常用瀏覽器差異處理
1.對象檢測:可通過條件分支語句及三元操作符檢測,例如:
function(){
if(typeOf(obj1)!='undefined'){
obj1();
}else {
obj2();
}
}
----------
typeOf(obj1) != 'undefined' ? obj1() : obj2();//三元操作符
2.判斷一個屬性是否存在最直接的方法是用JS對這個屬性賦值。
(需要修改)
添加與刪除事件:
添加事件在IE中 : attachEvent(“eventName”,func);
在FF中:addEventListener(“eventName”, func , bool );
其中bool裏true代表事件捕獲方式,false代表事件冒泡方式;
if(typeOf(document.addEventListenter != "undefined")){
document.addEventListenter("mousedowm",cli,true);//FF下
}else {
document.attachEvent("onmousedowm",cli);//IE下
}
刪除事件在IE中 :dettachEvent(“eventName”,func);
在FF中:removeEventListener(“eventName”, func , bool );
if(typeOf(document.removeEventListenter != "undefined")){
document.removeEventListenter("mousedowm",cli,true);//FF下
}else {
document.dettachEvent("onmousedowm",cli);//IE下
}
阻止事件的默認行爲:
比如阻止點擊a標籤後的跳轉
FF : preventDefault();
IE : window.event.returnValue = false;
<!DOCTYPE html>
<html>
<head>
<meta charset='UTF-8' />
<script>
/*阻止事件的默認行爲*/
function delDef(e){
if(e.preventDefault){
e.preventDefault();
}else{
window.event.returnValue = false;
}
return false;
}
window.onload =function(){
var elem = document.getElementById("a1");
elem.onclick = function(e){
delDef(e);
}
}
</script>
</head>
<body>
<a id = "a1" href="http://www.google.com">www.google.com</a>
<a href="http://www.google.com">www.google.com</a>
</body>
</html>
總結:以上介紹了常用解決瀏覽器兼容的辦法,並給出了事件添加與刪除、阻止時間的默認行爲的實例。主要用條件判斷與三元操作解決該問題。