如何防止图像地图区域点击传播到链接?
我有一个 HTML 图像地图,其中有一些带有链接的区域。我还有一些 Javascript 功能,在某些情况下,这些功能会覆盖某些特定区域的图像映射的默认功能。
我已通过此函数将我的函数附加到我想要的区域(其中 el
是元素,eventName
是事件的名称,eventHandler
> 是实际的函数):
function bindEvent(el, eventName, eventHandler)
{
if (el.addEventListener)
{
el.addEventListener(eventName, eventHandler, false);
}
else if (el.attachEvent)
{
el.attachEvent('on'+eventName, eventHandler);
}
}
因此,通过我的自定义处理程序,我正在执行以下操作:
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);
onAreaClick
函数实际上触发正常,但是我无法让事件停止传播。我尝试了 cancelBubble
、stopPropagation
和 return false
,但链接仍然有效。我还尝试在 bindEvent()
中的 addEventListener()
函数调用中将阶段从冒泡更改为捕获 。
如何阻止此事件触发图像映射的默认操作?
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 have 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
好的,经过一些更多的实验,我似乎让它在所有浏览器上运行,没有 JS 错误(或者看起来是这样)。
我创建了一个停止默认处理程序的函数,并以事件作为参数调用它。这个函数看起来像这样:
看起来工作正常,但欢迎评论。
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:
It seems to work OK, but comments appreciated.
你尝试过吗
Did you try