开发者

How to prevent Image map area click from propagating to link?

开发者 https://www.devze.com 2023-04-11 02:46 出处:网络
I have an HTML image map which has a few areas with links. I also have some Javascript functionality which, in certain cases, overrides the default functionality of the image map for some specific are

I have an HTML image map which has a few areas with links. I also have some Javascript functionality which, in certain cases, overrides the default functionality of the image map for some specific areas.

I ha开发者_StackOverflow中文版ve attached my function to the areas I want through this function (where el is the element, eventName is the name of the event and the eventHandler is the actual function):

function bindEvent(el, eventName, eventHandler) 
{
  if (el.addEventListener)
  {
    el.addEventListener(eventName, eventHandler, false); 
  } 
  else if (el.attachEvent)
  {
    el.attachEvent('on'+eventName, eventHandler);
  }
}

So through my custom handler I am doing something like this:

    function onAreaClick(e)
    {
             //my custom code here

        e.cancelBubble = true;
        if(e.stopPropagation) 
               e.stopPropagation();

        return false;
    }

    //...
    //assume looping through all areas of the imagemap here, with each element referred to by the variable area
    bindEvent(area, 'click', onAreaClick);

The onAreaClick function in fact triggers OK, however I can't get the event to stop propagating. I tried cancelBubble, stopPropagation, and return false, but the link is still followed through. I also tried to change the phase from bubbling to capturing in the addEventListener() function call in bindEvent().

How can I stop this event from triggering the default action of the image map?


OK, so after some more experimentation I seem to got it working on all browsers without JS errors (or so it seems).

I created a function that stops the default handler, and I called it with the event as argument. This function looks like this:

function stopDefaultHandler(e) 
{ 
    if (e)
    {
      e.cancelBubble = true;
      e.returnValue = false;

      if (e.stopPropagation)
        e.stopPropagation;

      if (e.preventDefault) 
       e.preventDefault();
    }

    if (window.event && window.event.returnValue)
       window.eventReturnValue = false;
}

It seems to work OK, but comments appreciated.


Did you try

e.preventDefault()
0

精彩评论

暂无评论...
验证码 换一张
取 消