思维导图内容:
如何使用JS事件,以及IE和标准DOM事件模型之间存在的差别。
主要是IE浏览器与其它主流浏览器的兼容性问题:
根据事件兼容性进行封装:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>侦听器</title>
</head>
<body>
<script>
var EventBus = {
addEventListener: function (element, type, handle, capture) {
if (element.addEventListener) {
element.addEventListener(type, handle, capture)
} else if (element.attachEvent) {
element.attachEvent('on' + type, handle)
} else {
element['on' + type] = handle
}
},
removeListener: function (element, type, handle) {
//移除事件为什么要传递handle呢?DOM2中绑定事件是可以绑定多个handle的,并不是所有handle都被移除,传进哪个就移除哪个
if (element.removeListener) {
element.removeListener(type, handle)
} else if (element.detachEvent) {
element.detachEvent('on' + type, handle)
} else {
element['on' + type] = null
}
},
getTarget: function (e) {
return e.target || e.srcElement
},
getEvent: function (e) {
return e || window.event
},
stopPropagation: function (e) {
if (e.stopPropagation) {
e.stopPropagation()
} else {
e.cancelBubble = true
}
},
preventDefault: function (e) {
if (e.preventDefault) {
e.preventDefault()
} else {
e.returnValue = false
}
},
}
</script>
</body>
</html>