[原创]js事件兼容
监听函数
if (el.addEventListener)...{
el.addEventListener('click', KindDisableMenu, false);
} else if (el.attachEvent)...{
el.attachEvent('onclick', KindDisableMenu);
}
IE中是attachEvent 和detachEvent Dom标准是addEventListener和removeEventLister。
attachEvent的第三个参数为useCapture
而useCapture這個參數就是在控制這時候兩個click事件的先後順序。如果是false,那就會使用bubbling,他是從內而外的流程,所以會先執行藍色元素的click事件再執行紅色元素的click事件,如果是true,那就是capture,和bubbling相反是由外而內
事件的类型 event.type
IE浏览器中事件对象是window对象的一个属性event
Op.onlick=function(){ var o = window.event}
而标准DOM中规定event对象必须作为唯一的参数传给事件处理函数
Op.onclick=function(oevent){
}
因此为了兼容两种浏览器,通常采用下面的方法
Op.onclick=function(o){
If(window.event)//假如不等于空,则为IE浏览器
O = window.event;
}
<script language="javascript">
function handle(oEvent){
var oDiv = document.getElementById("display");
if(window.event) oEvent = window.event; //处理兼容性,获得事件对象
if(oEvent.type == "click") //检测事件名称
oDiv.innerHTML += "你点击了我  ";
else if( oEvent.type == "mouseover")
oDiv.innerHTML += "你移动到我上方了  ";
}
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onclick = handle;
oImg.onmouseover = handle;
}
</script>
还有很多鼠标事件
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onmousedown = handle; //将鼠标事件除了mousemove外都监听
oImg.onmouseup = handle;
oImg.onmouseover = handle;
oImg.onmouseout = handle;
oImg.onclick = handle;
oImg.ondblclick = handle;
}
事件的激活元素 event.srcElement 或者 target
<script language="javascript">
function handle(oEvent){
if(window.event) oEvent = window.event; //处理兼容性,获得事件对象
var oTarget;
if(oEvent.srcElement) //处理兼容性,获取事件目标
oTarget = oEvent.srcElement; //IE支持的写法
else
oTarget = oEvent.target; //Firefox支持的写法
alert(oTarget.tagName); //弹出目标的标记名称
}
window.onload = function(){
var oImg = document.getElementsByTagName("img")[0];
oImg.onclick = handle;
}
</script>