簡體   English   中英

如何在js中一次添加所有事件監聽器?

[英]How to add all event listeners at once in js?

我正在創建某種 UI,並且我有一個在 JS 中創建聚光燈的想法。 這意味着如果用戶完全不與網站交互,例如 2 分鍾執行 function。 這讓我想到了一個問題:如何在任何事件發生后觸發 function

我想要這樣的東西:

document.addEventListener("all", spotlight)

我知道我可以做到,但這會很煩人,而且我知道必須有一些更優雅的解決方案

JS:

document.addEventListener(----, spotlight) 
 



function spotlight() {
     spotlightCanvas.classList.remove("hide")
}

謝謝。

您可以嘗試類似:事件列表

const event = ['click','focus'];

let watchdog = new Date();
event.forEach(ev=>{
    document.addEventListener(ev,_=>{
        watchdog = new Date();
    });
    
});
setInterval(_=>{
    if(new Date() - watchdog > 120000){
        spotlight();
    }
},100);

沒有一個事件可以代表所有事件,但你當然可以做你想做的事。 由於與網站交互的方式有很多種(鼠標點擊、鍵盤點擊、鼠標移動等),您需要設置一個計時器,當任何這些事件發生時,重置它。 如果計時器達到 120 秒,則可能會發生其他一些 function。

請參閱下面工作示例中的注釋,該注釋僅等待 5 秒。

 // Make an array of all the event names you want to listen for const event = ['click','mousemove', 'touchstart', 'keydown']; let maxSeconds = 5; // Amount of time document has to be inactive let inactive = 0; // Amount of time document has currently been inactive // This is a function that will run approximately every second let timer = setInterval(function(){ // If we add one to the inactive time and have reached the max... if(++inactive === maxSeconds){ spotlight(); // Run the desired function } }, 1000); // Run again in about a second // Loop over each of the strings in the array event.forEach(ev=>{ // Add an event listener for each event name document.addEventListener(ev, function(){ inactive = 0; // reset the amount of inactive time }); }); function spotlight(){ alert("Time's up;"); }

一個簡單的解決方案是只監聽mousemove事件。 用戶幾乎總是會在任何交互中移動鼠標。

每次鼠標移動時重置一個 2 分鍾計時器。 2分鍾無動作時, spotlight function運行。

let timer
window.addEventListener("mousemove",function(){
    clearTimeout(timer)
    timer = setTimeout(spotlight, 120000)
})
function spotlight(){
    console.lgo("the mouse disn't move for 2 minutes")
}

您可能會為不使用鼠標的用戶提供keydown事件選項,但我認為您不需要監聽所有事件。

暫無
暫無

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

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