簡體   English   中英

如何使事件偵聽器在單擊按鈕之前不偵聽?

[英]How to make an eventlistener not listen until a button gets clicked?

我正在開發這個游戲,有一個計時器,當用戶改變可見性時,我有這個事件監聽器,它警告用戶不要離開選項卡。 問題是,它在開始游戲的按鈕被點擊之前起作用。 JS 中有沒有辦法阻止事件偵聽器偵聽,直到單擊按鈕? 我嘗試循環刪除事件偵聽器並在單擊按鈕時停止循環功能,盡管它不起作用。 謝謝。

<!--This is the button that I want to start the eventlistener-->
<button onclick="start1game()" id="startgame">Continue</button>
<script>
document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});
</script>

沒有看到start1game()函數聲明我不能確定,但​​是如果你移動

document.addEventListener("visibilitychange", function() {
  alert('Please do not leave while playing the game.');
});

start1game()函數聲明中(作為第一行),那么在按下按鈕之前不會激活偵聽器。 如果這不能解決您的問題,我建議您編輯您的問題以包含更多代碼,但請記住,我們需要最少量的代碼來理解問題。

暫無
暫無

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

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