簡體   English   中英

頁面加載后,首次點擊被忽略

[英]First click is being ignored after page load

此網頁有一個簡單的事件偵聽器,當我右鍵單擊它時,它阻止打開上下文菜單。 很簡單。

但是,當我刷新頁面或在頁面初始加載時,如果我先用鼠標右鍵單擊該頁面,它將顯示上下文菜單,然后在每次單擊鼠標右鍵后都將其阻塞。 我在Chrome,FireFox和IE中嘗試過。 結果相同。

我在按下鼠標,按下鍵盤或觸摸事件等方面也遇到了同樣的事情。就像第一次單擊被忽略一樣。 我正在尋找JavaScript解決方案(而不是jquery)。 我想念什么?

<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>

我什至嘗試在事件偵聽器之前添加此內容(因為直到單擊窗口后才檢測到此后的keydown ), document.onload沒有運氣,並且確實發現瀏覽器可能專注於頁面加載設置。 我沒有在JavaScript中嘗試過的任何想法或其他想法嗎?

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

您不必兩次分配事件(如window.contextmenudocument.oncontextmenu )。 刪除多余的包裝似乎可行:

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

(取決於在文檔中放置addEventListener位置,也可能不需要window.onload 。)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM