[英]Avoid that click event for hoverable content triggering event click for parent element
如果我有这样的布局:
html
<div class="container" onclick="alert('clicked in the container');">
<img src="notebook.jpg" alt="Notebook" style="width:100%;">
<div class="content">
<button type="button" name="button" onclick="action(event, this);">test1</button> <button type="button" name="button" style="float: right;" onclick="action(event, this);">test2</button>
</div>
</div>
<script type="text/javascript">
function action(evt, elem) {
evt.preventDefault();
alert('clicked in '+elem.innerText);
}
</script>
css
.container {
position: relative;
max-width: 800px; /* Maximum width */
margin: 0 auto; /* Center it */
}
.container:hover .content {
display: block;
}
.container .content {
position: absolute; /* Position the background text */
bottom: 0; /* At the bottom. Use top:0 to append it to the top */
background: rgb(0, 0, 0); /* Fallback color */
background: rgba(0, 0, 0, 0.5); /* Black background with 0.5 opacity */
color: #f1f1f1; /* Grey text */
width: 100%; /* Full width */
padding: 20px; /* Some padding */
display: none;
}
我可以做什么,当我单击可悬停的.content
div 内的任何按钮时,不会触发父元素的事件单击? 现在,当我这样做时,会显示 2 个警报,显示消息“单击测试 x”,然后显示“单击容器”。
您应该停止事件传播(冒泡),因此您的父组件不会触发
无论如何,你应该摆脱 prevenDefault 你不需要它
<script type="text/javascript">
function action(evt, elem) {
evt.preventDefault();
evt.stopPropagation();
evt.stopImmediatePropagation();
alert('clicked in '+elem.innerText);
}
</script>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.