通过按 alt 键并单击 URL,Chrome 会进行下载。这是因为浏览器默认的 alt+click 操作。我怎样才能防止这种情况发生?它应该交换 url。
该代码适用于其他键(例如 x == 88),其中浏览器没有默认操作。但是如何使用 alt 键呢?
//ALT-key recognition
document.onkeydown=function(){
var keyCode = event.keyCode;
if(keyCode == 18) //alt-key
{
console.log(keyCode);
document.getElementById("hist").setAttribute ('href', "history_by-date.php?wdate=all");
}
}
<div id="history">
<a href="history_by-date.php?wdate=2018&until=2017" id="hist" target="_self" class="a2">should be just a link - not a download (when alt is pressed)</a>
</div><!-- end history -->
这里的另一位用户 skyline3000 有一个有趣的 article带有阻止代码,但我让它不起作用。感谢您的帮助。
evt.preventDefault();
evt.stopPropagation();
return false;
最佳答案
我认为您需要监听链接单击事件并检查 event.altKey 属性,而不是监听按键。我不是 100% 认为这是防弹与 Alt-click 下载,但它似乎有效。请注意,使用 this.click()
调用链接仅在正常 href、无 JavaScript 或点击事件时有效。否则还有其他更复杂的方法来完成该部分。
document.querySelectorAll('a').forEach(a => {
a.addEventListener('click', function (e) {
if (e.altKey) {
e.preventDefault(); // no download
this.href = 'history_by-date.php?watchdate=all';
this.click(); // fake a normal click
}
});
});
<a href='http://example.com'>alt-click me</a>
关于javascript - 如何覆盖默认的 Alt 键 + 单击操作?浏览器进行下载,但是,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53564044/