简体   繁体   中英

How to make the js function “onClick” work only on the container div?

I got a problem with the onClick function. 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.

<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.

Here's the 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() :

Inline script

<div onclick="event.stopPropagation();" id="new_msg_cont"></div>

jsFiddle

External script

div onclick="javascript:cancel(event);" id="new_msg_cont"></div>

javascript:

function cancel(e)
{
    e.stopPropagation();
}

jsFiddle

Try this approach:

<div id="msg_background" onclick="javascript:closemsg(this);">
  <div id="new_msg_cont">
     ... your code ...    
  </div>
</div>

JS CODE

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

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>

Inside your function check out if the event was fired by your parent div:

if (ev.target.id == "msg_background")
{
  //execute the contents of the closemsg function
}

(ev is the event parameter)

Working Demo: http://jsfiddle.net/kVuKA/1/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM