[原创]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 += "你点击了我&nbsp&nbsp;";

              else if( oEvent.type == "mouseover")

                            oDiv.innerHTML += "你移动到我上方了&nbsp&nbsp;";

                           

}

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>

转载于:https://www.cnblogs.com/520yang/articles/4409186.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值