简体   繁体   English

页面加载后,首次点击被忽略

[英]First click is being ignored after page load

This webpage has a simple event listener, when I right click it blocks opening the context menu. 此网页有一个简单的事件侦听器,当我右键单击它时,它阻止打开上下文菜单。 simple enough. 很简单。

But when I refresh the page or on initial load of the page, if I start with right mouse clicking the page, it shows the context menu, then blocks it ever time I right mouse click after that. 但是,当我刷新页面或在页面初始加载时,如果我先用鼠标右键单击该页面,它将显示上下文菜单,然后在每次单击鼠标右键后都将其阻塞。 I tried it in Chrome, FireFox and IE. 我在Chrome,FireFox和IE中尝试过。 Same results. 结果相同。

I experience the same thing with mouse down, keydown, or touch events, etc. It is like the first click is ignored. 我在按下鼠标,按下键盘或触摸事件等方面也遇到了同样的事情。就像第一次单击被忽略一样。 I am looking for JavaScript solution (not jquery). 我正在寻找JavaScript解决方案(而不是jquery)。 What am I missing? 我想念什么?

<html>
<head>
<title>test</title>
<script type="text/javascript">
window.onload = function () {
    window.addEventListener("contextmenu", mouseright);
}
function mouseright() {
    document.oncontextmenu = function(e) {
        var e = e || window.event;
        alert("right");
        e.preventDefault();
    }
}
</script>
</head>
<body>
hello world
</body>
</html>

I even tried adding this before the event listener (as in this post keydown not detected until window is clicked ), had no luck with document.onload and did see that it could be a possible browser focus on page load setting. 我什至尝试在事件侦听器之前添加此内容(因为直到单击窗口后才检测到此后的keydown ), document.onload没有运气,并且确实发现浏览器可能专注于页面加载设置。 Any thoughts or other ideas I didn't try in JavaScript? 我没有在JavaScript中尝试过的任何想法或其他想法吗?

if (document.hasFocus() == true) {
  } else {
    window.focus();
  }

You're unnecessarily assigning the event twice (as both window.contextmenu and document.oncontextmenu ). 您不必两次分配事件(如window.contextmenudocument.oncontextmenu )。 Removing the extra wrapper seems to work: 删除多余的包装似乎可行:

window.onload = function () {
    window.addEventListener("contextmenu", mouseright);
}
function mouseright(e) {
    var e = e || window.event;
    alert("right");
    e.preventDefault();
}

(The window.onload may also be unneeded, depending on where you place the addEventListener in the document.) (取决于在文档中放置addEventListener位置,也可能不需要window.onload 。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM