Home  >  Article  >  Web Front-end  >  JS在IE和FF下attachEvent,addEventListener学习笔记_javascript技巧

JS在IE和FF下attachEvent,addEventListener学习笔记_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:41:071046browse

对象名.addEventListener("事件名(不带ON)",函数名,true/false);(FF下)
对象名.attachEvent("事件名",函数名);(IE下)
说明:
  事件名称,要注意的是"onclick"要改为"click","onblur"要改为"blur",也就是说事件名不要带"on"。
函数名,记住不要跟括号最后一个参数是个布尔值,表示该事件的响应顺序,下面重点介绍一下addEventListener的第3个参数(useCapture)。 userCapture若为true,则浏览器采用Capture,若为false则采用bubbing方式。建议用false,看个例子吧。
html代码


js代码
复制代码 代码如下:

window.onload=function(){ document.getElementById("div_test").addEventListener("click",test1,false); document.getElementById("btn_test").addEventListener("click",test2,false); } function test1(){ alert("外层div触发") } function test2(){ alert("内层input触发") }

自己体验一下,如果userCapture是true则test1先触发,如果userCapture是false则test2先触发。

下面来说一下,attachEvent
这个没啥好说的,相信大家也都用的挺熟的,主要是传参那块,等我用到 再说吧,哈哈哈

示例:
创建绑定方法:
复制代码 代码如下:

if (typeof document.addEventListener != "undefined") {
document.addEventListener("mousedown",_lhlclick,true);
} else {
document.attachEvent("onmousedown",_lhlclick);
}

删除事件:
复制代码 代码如下:

if (typeof document.addEventListener != "undefined") {
document.removeEventListener("mousedown",_lhlclick,true);
} else {
document.detachEvent("onmousedown",_lhlclick);
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn