【发布时间】:2019-06-22 12:27:49
【问题描述】:
我可以进入 contextmenu 对象并禁用它 (How to add a custom right-click menu to a webpage?),但是当用户右键单击链接对象并选择“在新选项卡中打开”或“在新窗口”还是“在隐身窗口中打开”?
【问题讨论】:
标签: javascript html hyperlink href contextmenu
我可以进入 contextmenu 对象并禁用它 (How to add a custom right-click menu to a webpage?),但是当用户右键单击链接对象并选择“在新选项卡中打开”或“在新窗口”还是“在隐身窗口中打开”?
【问题讨论】:
标签: javascript html hyperlink href contextmenu
事实上,我找到了一种更好/更简单的方法来实现它。 replaceLink() 负责替换此处的centextmenu链接:
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<a href="https://majkesz.pl" id="lol" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
<script>
document.getElementById("lol").onclick = function(event) {
event.preventDefault();
window.location.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
return false;
};
function replaceLink(e) {
e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
}
</script>
</body>
</html>
不幸的是,上述解决方案不适用于 FF 和较新的 chrome 鼠标中键单击。而是使用泛型:
<html>
<head>
<meta charset="utf-8"/>
</head>
<body>
<a href="https://majkesz.pl" onmousedown="replaceLink(event)" oncontextmenu="replaceLink(event);">majkesz.pl</a><br>
<script>
function replaceLink(e) {
e.target.href = "https://www.youtube.com/watch?v=oHg5SJYRHA0";
}
</script>
</body>
</html>
【讨论】:
在我看来,出于安全原因,您无法这样做。要与上下文菜单交互,您可以查看此库 http://ignitersworld.com/lab/contextMenu.html。
编辑:你可以试试这个,虽然它有点 hacky。
<html>
<head>
</head>
<body>
<a href="http://www.google.com">Google</a>
<script>
// get all anchor elements
var anchors = document.getElementsByTagName("a");
for(var i=0; i<anchors.length; i++){
var el = anchors[i];
// add event listener on each anchor element
el.addEventListener('contextmenu', function(ev) {
// get the original href value of the element
var originalTarget = el.href;
// change it to what you want to go to
el.href = 'http://www.amazon.com';
// asynchonously change it back to the original
setTimeout(function(){
el.href = originalTarget;
},1);
}, false);
}
</script>
</body>
</html>
它在所有锚元素上添加一个事件侦听器,并在触发上下文菜单事件时更改 href,然后将其更改回其原始值。希望它对你有用。
【讨论】: