[英]prevent link click event except open in new window hotkey is pressed
So I have my website, a website without reload between site switches.所以我有我的网站,一个没有在站点切换之间重新加载的网站。 For SEO reasons, my links look like this:出于 SEO 原因,我的链接如下所示:
<a href="/site2" id="viewmore">View more</a>
<script>
// code is strongly simplified, for more clarity
document.getElementById("viewmore").addEventListener("click",function(e) {
e.preventDefault();
myHandler.goTo(e.currentTarget.href);
});
</script>
myHandler is the site handler in this case.在这种情况下,myHandler 是站点处理程序。
If I click the hotkey for opening a link in a new tab (on Mac it is CMD+Click), it does not work, as the event is prevented.如果我单击用于在新选项卡中打开链接的热键(在 Mac 上是 CMD+Click),它不起作用,因为该事件被阻止。
How to check if the link should open in a new tab or not?如何检查链接是否应该在新标签页中打开? (Check if the hotkey is pressed or not) (检查热键是否被按下)
Not sure I understood it, but try this不确定我是否理解它,但试试这个
document.getElementById("viewmore").addEventListener("click", (e) => {
// ctrlKey / altKey / shiftKey
if (e.ctrlKey) myHandler.goTo(e.currentTarget.href);
else e.preventDefault();
});
You can store the state of the CMD key in a variable and check it when the link is clicked.您可以将 CMD 密钥的 state 存储在变量中,并在单击链接时进行检查。
let isCmdPressed = false;
document.addEventListener("keydown",(e)=>{
if (e.key == "Meta"){
isCmdPressed = true;
}
});
document.addEventListener("keyup",(e)=>{
if (e.key == "Meta"){
isCmdPressed = false;
}
});
document.getElementById("viewmore").addEventListener("click",function(e) {
if (!isCmdPressed){
e.preventDefault();
myHandler.goTo(e.currentTarget.href);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.