[英]How to make the js function “onClick” work only on the container div?
我在onClick函數上遇到了問題。 我必須設定
display: none;
當用戶單擊時,在css容器div中單擊,但在單擊容器中的div時未單擊。
<div id="msg_background" onclick="javascript:closemsg();">
<div id="new_msg_cont">
</div>
</div>
因此,我不希望單擊“ new_msg_cont”該功能仍然有效。
這是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';
}
提前致謝。
試試這種方法:
<div id="msg_background" onclick="javascript:closemsg(this);">
<div id="new_msg_cont">
... your code ...
</div>
</div>
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';
}
}
嘗試這樣的事情
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
<div id="msg_background" onclick="closemsg(event);">
div1
<div id="new_msg_cont">
div2
</div>
</div>
在函數內部檢查事件是否由您的父div觸發:
if (ev.target.id == "msg_background")
{
//execute the contents of the closemsg function
}
(ev是事件參數)
工作演示: http : //jsfiddle.net/kVuKA/1/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.