Dom事件的级别
Dom事件模型(冒泡+捕获)
Dom事件流
http://www.cnblogs.com/starof/p/4066381.html
image.png<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Event</title>
</head>
<body>
<div id="ev">
<style>
#ev {
width: 300px;
height: 100px;
background: red;
color: #fff;
text-align: center;
line-height: 100px;
}
</style>
目标元素
<script>
var ev=document.getElementById("ev");
// true捕获阶段触发,false冒泡阶段触发
window.addEventListener("click", function(){
console.log("window captrue");
}, false);
ev.addEventListener("click", function(){
console.log("ev captrue");
}, false);
document.addEventListener("click", function() {
console.log("document captrue");
}, false);
document.documentElement.addEventListener("click", function(){
console.log("html captrue");
}, false);
document.body.addEventListener("click", function(){
console.log("body captrue");
}, false);
// 自定义事件
var eve = new Event('test');
ev.addEventListener('test', function(){
console.log('test dispatch');
})
setTimeout(function() {
ev.dispatchEvent(eve);
}, 1000);
// 自定义事件CustomEvent
// new一个CustomEvent构造函数的实例允许你通过两个特殊的属性事件名称和数量来创建自定义事件。dispatchEvent触发事件在给定的元素。让我们通过两个参数bubbling, cancelable来触发自定义事件。
ev.addEventListener("userLogin", function(e) {
console.info("Event is: ", e);
console.info("Custom data is: ", e.detail);
})
// var myEvent = new CustomEvent ( 'userLogin', {
// detail: {
// username: "***"
// }
// });
var myEvent = new CustomEvent("userLogin", {
detail: {
username: "****"
},
bubbles: true,
cancelable: false
});
ev.dispatchEvent (myEvent);
</script>
</div>
</body>
</html>
网友评论