如何不使用锚点标签,纯用JavaScript实现点击图片新标签页打开链接
解决点击图片在新标签页打开链接的问题
直接用 window.open() 替代 window.location.href 就能实现需求,这个方法支持指定打开目标。修改后的点击事件代码如下:
document.querySelector("#discordInv").addEventListener("click", () => { window.open("https://discord.gg/52BTDY", "_blank"); });
说明:
window.open()的第一个参数是要打开的链接地址,第二个参数"_blank"表示在新标签页打开。- 由于这个调用是在用户点击事件的回调中触发,浏览器不会将其判定为恶意弹窗,可正常打开。
另外,也可以在创建图片元素时直接绑定事件,无需事后通过 querySelector 获取元素,代码更简洁:
let discordLogo = document.createElement("img"); discordLogo.setAttribute( "src", "https://media.discordapp.net/attachments/1079211646746099792/1079217653916377148/discord.png?width=470&height=470" ); discordLogo.style.width = "40px"; discordLogo.style.height = "40px"; discordLogo.style.position = "absolute"; discordLogo.style.top = "14px"; discordLogo.setAttribute("id", "discordInv"); discordLogo.style.right = "75px"; // 直接绑定点击事件 discordLogo.addEventListener("click", () => { window.open("https://discord.gg/52BTDY", "_blank"); }); main.appendChild(discordLogo);
内容的提问来源于stack exchange,提问作者Below Mid Developer
相关产品推荐
相关产品推荐

