HTML DOM stopPropagation() 事件方法
HTML DOM stopPropagation() 事件方法用於停止給定元素的傳播。這意味著單擊父元素不會傳播到子元素中,使用 stopPropagtion() 方法單擊子元素也不會傳播到父元素中。事件傳播也稱為事件冒泡。
語法
以下是在 stopPropagation() 事件方法中: -
event.stopPropagation()
示例
讓我們看一個 stopPropagation() 事件方法的例子: -
<!DOCTYPE html> <html> <head> <style> #DIV_1 { background: lightpink; width:130px; height:130px; margin-left:40%; text-align:center; } #IMG_1 { width:100px; height:100px; position:relative; left:5px; } </style> </head> <body> <h1>stopPropagation() method example</h1> <div id="DIV_1" onclick="OuterDiv()"> DIV ELEMENT <img onclick="InnerImg(event)" id="IMG_1" src="https://tutorialspoint.tw/hibernate/images/hibernate-mini-logo.jpg"> </div> Stop propagation: <input type="checkbox" id="check"> <script> function InnerImg(event) { confirm("Inner Image is clicked"); if (document.getElementById("check").checked) { event.stopPropagation(); } } function OuterDiv() { confirm("Outer div is clicked"); } </script> </body> </html>
輸出
這會生成以下輸出: -
在未單擊停止傳播方法之前單擊 div 元素內的 Image 元素: -
單擊上面的“確定”: -
選中停止傳播複選框,然後單擊內部影像: -
廣告