How can I stop an onclick event from firing for parent element when child is clicked?(单击子元素时,如何阻止 onclick 事件触发父元素?)
问题描述
我有两个关于 onclick 事件的问题,它们有点相似,所以我会在这里问他们.
I'm having two issues with onclick events, they are somewhat similar so I'll ask them both here.
第一:
我在 div 中有一个复选框.输入有onchange函数,div有onclick函数.
I have a checkbox in a div. The input has an onchange function and the div has an onclick function.
<div onclick="doSomething()">
<input type="checkbox" onchange="doSomethingElse()" />
</div>
问题是当我选中/取消选中复选框时,doSomething() 和 doSomethingElse() 都会触发.关于如何阻止这种情况发生的任何想法?我试过做 onchange="doSomethingElse(event)" 和 doSomethingElse(e) 函数我有 e.stopPropagation();这没有用.
The problem is when I check/uncheck the checkbox both doSomething() and doSomethingElse() fire. Any ideas of how to stop this from occuring? I've tried doing onchange="doSomethingElse(event)" and the in doSomethingElse(e) function I had e.stopPropagation(); and this did not work.
第二:
我在 div 中有一张图片.div 具有 onclick 功能,但图像没有.图像故意大于 div 并溢出到 div 之外.
I have an image in a div. The div has an onclick function but the image does not. The image is, purposely, larger than the div and overflows outside the div.
-----------------------
| image |
| --------------- |
| | div | |
| | | |
| --------------- |
| |
-----------------------
我只希望用户在 div 框的范围内单击时触发 onclick.但是,如果您单击已溢出到 div 外部的图像的一部分,也会触发 onclick 事件......有什么想法吗?
I only want the onclick to fire if the user clicks within the bounds of the div box. However, the onclick event also fires if you click on a part of the image that has overflowed to the outside of the div... Any ideas?
第一个问题对我来说比第二个问题更重要.但如果有人能同时回答这两个问题,那就太棒了!
The first question is more important to me than the second. But if someone can answer both that would be awesome!
提前感谢您的帮助,
马特
Thanks in advance for your help,
Matt
推荐答案
第一个问题:IE不支持stopPropagation()
,你应该使用e.cancelBubble = true代码>.只需先做一个函数检查,看看你应该使用哪种方法(
if (e.stopPropagation) {code}
).
For your first question: IE doesn't support stopPropagation()
, instead you should use e.cancelBubble = true
. Just do a function check first to find out which method you should use (if (e.stopPropagation) {code}
).
对于您的第二个问题:也许包括处理点击事件的第二个 div?
For your second question: Maybe include a second div that handles the click event?
<div><img src="image.jpg"/></div>
<div style="position:absolute" onclick="doSomething();"></div>
然后正确定位第二个div
and then position the second div correctly
这篇关于单击子元素时,如何阻止 onclick 事件触发父元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:单击子元素时,如何阻止 onclick 事件触发父元素
基础教程推荐
- Vue 3 – <过渡>渲染不能动画的非元素根节点 2022-01-01
- 如何使用TypeScrip将固定承诺数组中的项设置为可选 2022-01-01
- html表格如何通过更改悬停边框来突出显示列? 2022-01-01
- 自定义 XMLHttpRequest.prototype.open 2022-01-01
- 如何使用JIT在顺风css中使用布局变体? 2022-01-01
- 我可以在浏览器中与Babel一起使用ES模块,而不捆绑我的代码吗? 2022-01-01
- 直接将值设置为滑块 2022-01-01
- 用于 Twitter 小部件宽度的 HTML/CSS 2022-01-01
- Electron 将 Node.js 和 Chromium 上下文结合起来意味着 2022-01-01
- Chart.js 在线性图表上拖动点 2022-01-01