HTML:
<p id="container">
<p id="inner">
</p>
</p>
JS:
document.getElementById('container').addEventListener('click',function () {
document.getElementById('inner').style.display = "none";
});
When I click on the child element, it will disappear. How to avoid this situation? I don't want to bind click events to child elements as well.
曾经蜡笔没有小新2017-06-12 09:24:56
document.getElementById('container').addEventListener('click',function (e) {
document.getElementById('inner').style.display = "none";
e.stopPropagation();
}, true);
Pass the third parameter true
to addEventListener
. Use event capture.
https://developer.mozilla.org...
e.stopPropagation()
Stop event propagation.
https://developer.mozilla.org...
仅有的幸福2017-06-12 09:24:56
https://jsfiddle.net/g5u7qrrd/6/
document.getElementById('container')
.addEventListener('click',function (e) {
if (e.target.id !== 'inner')
document.getElementById('inner').style.display = "none";
});
仅有的幸福2017-06-12 09:24:56
Add pointer-events: none;
to the sub-element style and ignore mouse events directly. IE may need to be compatible.