[英]How to make the js function “onClick” work only on the container div?
I got a problem with the onClick function. 我在onClick函数上遇到了问题。 I have to set
我必须设定
display: none;
in a css container div when the user clicks on it, but not when he clicks on the divs which are in the container. 当用户单击时,在css容器div中单击,但在单击容器中的div时未单击。
<div id="msg_background" onclick="javascript:closemsg();">
<div id="new_msg_cont">
</div>
</div>
So, i don't want that clicking on "new_msg_cont" the function still works. 因此,我不希望单击“ new_msg_cont”该功能仍然有效。
Here's the js: 这是js:
function closemsg() {
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
Thanks in advance. 提前致谢。
This is called "bubbling" where the inner elements event 'bubbles' up to the parent element. 这称为“起泡”,其中内部元素事件“起泡”到父元素。
You can cancel this with event.stopPropagation()
: 您可以使用
event.stopPropagation()
取消此操作:
Inline script 内联脚本
<div onclick="event.stopPropagation();" id="new_msg_cont"></div>
External script 外部脚本
div onclick="javascript:cancel(event);" id="new_msg_cont"></div>
javascript: javascript:
function cancel(e)
{
e.stopPropagation();
}
Try this approach: 试试这种方法:
<div id="msg_background" onclick="javascript:closemsg(this);">
<div id="new_msg_cont">
... your code ...
</div>
</div>
JS CODE JS代码
function closemsg(ele) {
if(ele.id === 'msg_background'){
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
try something like this 尝试这样的事情
javascript javascript
function closemsg(event) {
if(event.target.id == "msg_background" ){
alert('you cliked me');
document.getElementById('cont').style.height='';
document.getElementById('cont').style.overflow='';
document.getElementById('cont').style.position='';
document.getElementById('msg_background').style.display='none';
}
}
html html
<div id="msg_background" onclick="closemsg(event);">
div1
<div id="new_msg_cont">
div2
</div>
</div>
Inside your function check out if the event was fired by your parent div: 在函数内部检查事件是否由您的父div触发:
if (ev.target.id == "msg_background")
{
//execute the contents of the closemsg function
}
(ev is the event parameter) (ev是事件参数)
Working Demo: http://jsfiddle.net/kVuKA/1/ 工作演示: http : //jsfiddle.net/kVuKA/1/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.