<div style="width:100px;height:100px;border:1px solid red;overflow:auto;" id="box"> <div style="width:50px;height:50px;border:1px solid red" id="content"></div> </div>html元素
1、js系結事件分為冒泡和捕獲兩種情況
2、冒泡執行順序,先執行子元素的事件,再執行父元素的事件
3、捕獲執行順序,先執行父元素的事件,再執行子元素的事件
4、在既有捕獲又有冒泡的情況下,先從外層一層一層往內執行捕獲,一直到目標元素,目標元素按照系結順序執行,然后繼續往外執行冒泡,這個是自己測驗出來的結果,僅代表個人看法,和網上很多人的說法不一樣,也歡迎大佬指正,
這里將流程劃分為三部分:1、從外往內執行捕獲, 2、達到目標元素后,按系結順序執行,3、從內往外冒泡
5、dom影片發生時,取到的dom資料是影片前的
6、停止事件的傳播 e.stopPropagation();
在4的流程中,執行e.stopPropagation()可以讓事件不傳播的下一步驟,并且不傳播的下一個dom節點,在第二步的同dom節點不受影響,
if (!window.addEventListener) {
//兼容IE8
window.addEventListener = window.attachEvent;
}
$("#content").click(function (e) {
//$(this).height(200); //第一次,直接改變高度
$(this).animate({ "height": 200 }, 2000, function () {
console.log("end");
}).stop(true, true);//第二次,緩慢改變高度
//e.preventDefault();
console.log("content 冒泡1");
});
$("#content").click(function (e) {
console.log('content 冒泡2', $(this).height());
});
$("#content").on("click", function () {
console.log('content 冒泡3', $(this).height());
});
$("#content")[0].addEventListener("click", function (e) {
console.log('content 捕獲1', $(this).height());
}, true);
$("#content")[0].addEventListener("click", function () {
console.log('content 捕獲2', $(this).height());
}, true);
$("#box").click(function () {
console.log('box 冒泡1', $("#content").height());
});
$("#box").on("click", function () {
console.log('box 冒泡2', $("#content").height());
});
$("#box")[0].addEventListener("click", function (e) {
console.log('box 捕獲1', $("#content").height());
e.stopPropagation();
}, true);
$("#box")[0].addEventListener("click", function (e) {
console.log('box 捕獲2', $("#content").height());
//e.stopPropagation();
}, true);
$("#box").on("scroll", function () {
console.log("resize");
});
demo
7、jquery on 系結
jquery on 可以將子dom的事件綁到父節點上,執行順序是 1、系結在子節點的事件,2、系結在父節點的子節點的事件 3、父節點的事件
$("#box").on("click", function () {
console.log('box 冒泡1', $(this).height());
});
$("#box").on("click","#content", function () {
console.log('content 冒泡2', $("#content").height());
});
$("#content").on("click", function () {
console.log('content 冒泡3', $(this).height());
});
on 的順序
8、各種系結冒泡事件的總結
1.選擇器匹配到的元素比較多時,不要用bind() 或者 click(function(){})迭代系結,會系結很多事件
2.用delegate()或者on(),可以動態給子節點添加的系結事件,系結這個節點不能是動態的,
3.用delegate()和on()方法,dom樹不要太深,因為一層一層冒泡上來影響性能,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/239966.html
標籤:JavaScript
