酷符网Web前端 > 正文

javascript函数addEventListener() attachEvent()的使用

2010-12-22 17:24codeif.com

W3C DOM(Document Object Model)模型可以分为两种,DOM0 和 DOM2

DOM0 和 DOM1的事件(event)如下

DOM 0 Event DOM 2 Event
onblur() blur
onfocus() focus
onchange() change
onmouseover() mouseover
onmouseout() mouseout
onmousemove() mousemove
onmousedown() mousedown
onmouseup() mouseup
onclick() click
ondblclick() dblclick
onkeydown() keydown
onkeyup() keyup
onkeypress() keypress
onsubmit() submit
onload() load
onunload() unload

DOM2中的Event可以addEventListener()这个函数来添加
addEventListener(event,function,capture/bubble);

参数说明:event如上表(DOM2列)所示, function是要执行的函数, capture和bubble分別W3C的两种时间模式,capture是document的开始的第一行到最后一行, 再执行Event事件, bubble是先寻找指定的位置在执行Event事件.
capture/bubble的参数是布尔型(boolean), true表示用capture, false表示bubble .IE有自己特殊的EventHandler, 是 attachEvent(), 格式如下:

attachEvent(event, myFunction());

attachEvent不需要指定capture/bubble的参数, 默认使用Bubble的模式.

在使用之前可以判断一下浏览器是否支持addEventListener 或者 attachEvent
判断方式如下
if (window.attachEvent) {
alert(“支持attachEvent”);
} else {
if (window.addEventListener) {
alert(“支持addEventListener”);
}
}

这两个函数主要用来给摸个元素绑定Event事件,我们可以写一个函数来帮给指定元素注册Event事件
function regEvent(ele, event_name, fun) {
var e_name = event_name.replace(/^on/, “”); //如果on开头,删除,如onclick->click
if (window.attachEvent) {
ele.attachEvent(“on” + e_name, fun)
} else {
if (window.addEventListener) {
ele.addEventListener(e_name, fun, false)
}
}
}

我们写一个 点击某个元素执行 指定函数的例子,代码如下:

<!doctype html>
<html>
<head>
<meta charset="utf-8" />
<title>addEventListener与attachEvent测试</title>
<script type="text/javascript">
function f(){
    alert("执行f()函数");
}
function regEvent(ele, event_name, fun) {
    var e_name = event_name.replace(/^on/, ""); //如果on开头,删除,如onclick->click
    if (window.attachEvent) {
        ele.attachEvent("on" + e_name, fun)
    } else {
        if (window.addEventListener) {
            ele.addEventListener(e_name, fun, false)
        }
    }
}
function init(){
    var a = document.getElementById("codeif_id");
    regEvent(a, "click", f);
}
window.onload = init;
</script>
</head>
<body>
<a id="codeif_id" href="javascript:void(0);">点下看看</a>
</body>
</html>

相关文章

新浪微博 | 淘段子 | 我的博客 | 淘宝店铺 | jnan.org | RSS
Copyright © 2009 - 2011 酷符网