retain links functionality inside a div that has a

2019-07-21 02:21发布

问题:

I have a div that has an onclick that hides the div.

If I have a link inside the div, the link does not work, because the onclick steals the click.

The desired result: if a click is made anywhere inside the div BUT the link, that the div gets hidden. If a click is made ON the link, then I want the link to open in a _blank window, and the div to remain visible.

Is there a way to deal with this with javascript?

回答1:

DEMO

Inside the click handler for the link, you'll want to call event.stopPropagation, or set e.cancelBubble to true—whichever your browser prefers. This will prevent the event from bubbling to your div.

document.getElementById("thelink").onclick = function (e) {
    window.open();
    if (e.stopPropogation)
        e.stopPropogation();
    if (e.cancelBubble != null)
        e.cancelBubble = true;
};


回答2:

document.getElementById('yourlinksid').onclick = function(e){

   // ... pop your window ...

   /* the following prevents the event from "bubbling up"
      to the div's event handler */
   if(!e.stopPropagation) {
      e.cancelBubble = true;
      return;
   }

   e.stopPropagation();    
};

Verification:

http://jsfiddle.net/kSTNT/4/



回答3:

If you control the links, the easiest way is to add onclick="event.stopPropagation();" (or whatever the cross-browser version of that is) to each link, which stops the div from seeing the event without preventing the default effect of the link from taking place.

Alternatively, if the links only contain text, then you can check the tag name of the event's target in the div's click event to see whether it is a link, but if you have something more complex then you need to walk the dom tree from the event target to the div to verify that no link exists.