-
Notifications
You must be signed in to change notification settings - Fork 0
/
封装event方法.html
108 lines (104 loc) · 3.27 KB
/
封装event方法.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>event</title>
</head>
<body>
<ul id="nav">
<li><a href="http://11111">111</a></li>
<li><a href="http://2222">222</a></li>
<li><a href="http://333">333</a></li>
<li><a href="http://444">444</a></li>
</ul>
</body>
<script>
// 使用原生javascript给下面列表中的li节点绑定点击事件,点击时创建一个Object对象,兼容IE和标准浏览器
var EventUtil = {
on: function (el, type, handler) {
if (window.addEventListener) {
el.addEventListener(type, handler, false)
return handler
} else if (window.attachEvent) {
var wrapper = function (event) {
handler.call(el, event)
}
el.attachEvent('on' + type, wrapper)
return wrapper
} else {
el['on' + type] = handler
return handler
}
},
off: function (el, type, handler) {
if (window.removeEventListener) {
el.removeEventListener(type, handler, false)
} else if (window.detachEvent) {
el.detachEvent('on' + type, handler)
} else {
el['on' + type] = false
}
},
//禁用默认行为
prevent: function (event) {
if (event.preventDefault) {
event.preventDefault();
} else {
event.returnValue = false;
}
},
//阻止事件冒泡
stop: function (event) {
if (event.stopPropagation) {
event.stopPropagation();
} else {
event.cancelBubble = true;
}
},
//获取事件
getEvent: function (event) {
return event || window.event;
},
getTarget: function (event) {
return event.target || event.srcElement;
},
//获取事件类型
getType: function (event) {
return event.type;
},
}
var DOMUtil = {
text: function (el) {
if ('textContent' in el) {
return el.textContent
} else {
return el.innerText
}
},
prop: function (el, propName) {
return el.getAttribute(propName)
}
}
var nav = document.getElementById('nav')
EventUtil.on(nav, 'click', function (event) {
EventUtil.prevent(event)
var event = EventUtil.getEvent(event)
var target = EventUtil.getTarget(event)
// console.log(target, this.children)
var children = this.children
var result = {}
for (var i = 0, len = children.length; i < len; i++) {
if (target === children[i].firstChild) {
console.log('===')
result['index'] = i + 1
result['name'] = DOMUtil.text(target)
result['link'] = DOMUtil.prop(target, 'href')
}
}
console.log(result)
return result
})
</script>
</html>