在具有onclick事件的div中保留链接功能 [英] retain links functionality inside a div that has an onclick event

查看:82
本文介绍了在具有onclick事件的div中保留链接功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个div,其中的onclick隐藏了div.

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

如果我在div内有一个链接,则该链接不起作用,因为onclick会窃听点击.

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

理想的结果:如果在div内的任何位置单击,但该链接被隐藏,则div被隐藏.如果单击该链接,则我希望该链接在_blank窗口中打开,并且div保持可见.

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.

有没有办法用javascript处理这个问题?

Is there a way to deal with this with javascript?

推荐答案

演示

在链接的点击处理程序中,您需要调用 event.stopPropagation ,或将e.cancelBubble设置为true(无论您使用哪种浏览器).这样可以防止事件冒泡到您的div.

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;
};

这篇关于在具有onclick事件的div中保留链接功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆