兩個div疊在一起各自呼叫不同的方法/ 阻止子元素的click事件冒泡到父元素 /event.stopPropagation() 的使用
阿新 • • 發佈:2021-11-09
1、效果圖:
2、event.stopPropagation() 定義
菜鳥教程:https://www.runoob.com/jquery/event-stoppropagation.html
3、例子:
點選檢視程式碼
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>阻止子元素的click事件冒泡到父元素</title> </head> <style> .parent{ width: 300px; height: 200px; background-color: #1E9FFF; } .children{ width: 30%; height: 40%; padding: 20px; background-color: #8A2BE2; } </style> <body> <div class="parent" id="parent"> <div class="children" id="children">子元素</div> <br />父元素 </div> </body> <script type="text/javascript" src="../../js/jquery-3.5.1.min.js" ></script> <script> $("#parent").click(function(){ alert("你點選了父元素的方法!"); }); $("#children").click(function(event){ event.stopPropagation(); // 阻止子元素(input)的click事件冒泡到父元素(div) alert("你點選了子元素的方法.......") }); </script> </html>