簡體   English   中英

如何檢測何時在 js 中按住按鈕?

[英]How can I detect when a button is held in js?

我試圖檢測一個按鈕何時被手指按住一段未指定的時間。 但是我不知道該怎么做。

我嘗試這樣做,就像在線示例顯示的那樣

 const b = document.getElementById("hold-me"); b.onclick = function() { setTimeout(alert, 2000, "you held me down for 2 second"); }
 <body> <button id="hold-me">Hold me</button> </body>

但是,它不符合我想要做的事情,因為我希望只要按下按鈕就能夠觸發事件。

編輯:

為了澄清一下,設置超時 function 在這里,因為它大致就是我在網上找到的示例所做的。 這是示例: https://codepen.io/thetallweeks/pen/uAEGr?editors=0010

我在網上找到的示例沒有幫助,因為我想查詢是否連續按下按鈕以了解我是否應該移動我的遙控車。

第一個變體,在“未指定時間”后觸發事件;

 const b = document.getElementById("hold-me"); let time; b.onpointerdown = function() { time = Date.now(); } b.onpointerup = function() { console.log(`you held me down for ${Date.now() - time} milliseconds`); }
 <body> <button id="hold-me">Hold me</button> </body>

第二個變體,在“未指定的時間”內觸發事件:

 const b = document.getElementById("hold-me"); let timer; b.onpointerdown = function() { timer = setTimeout(alert, 2000, "you held me down for 2 second"); } b.onpointerup = function() { clearTimeout(timer); }
 <body> <button id="hold-me">Hold me</button> </body>

每次按下按鈕時,使用mousedown事件並獲取當前時間。 然后,在計時器 function 中,查看它是否至少是用戶確定的超過該開始時間的秒數。 松開按鈕后,重新設置時間。

此外,您應該使用現代 API 進行 .addEventListener .addEventListener()的事件綁定,而不是設置事件屬性。

 let start = null; const elapsedTime = +prompt("How many seconds should we wait?"); const button = document.getElementById("hold-me"); button.textContent += " for at least " + elapsedTime + " seconds."; button.addEventListener("mousedown", function() { start = new Date(); // Record the start time setTimeout(function(){ // If there is a start time and its now at least 2 seconds past that... if(start && (new Date() > start.setSeconds(start.getSeconds() + elapsedTime))){ alert("You held me down for " + elapsedTime + " seconds."); } }, elapsedTime * 1000); }); document.getElementById("hold-me").addEventListener("mouseup", function() { start = null; // Cancel the time });
 <button id="hold-me">Hold me</button>

這取決於您認為用戶持有多少時間。 例如,您可以說,少於 1 秒的時間是單擊,而更大的時間是按住按鈕。

此外,值得指出的是,holding 是兩個 Javascript 事件的組合: mouseupmousedown 第一個跟蹤單擊是否按下按鈕,第二個跟蹤用戶離開鼠標單擊按鈕。

 let startTime, clickTime = 2000 // in milliseconds $("#btn").mousedown(()=>{ startTime = new Date() console.log("Holding") // Your logic goes here (while holding) }) $("#btn").mouseup(()=>{ var elapsedTime = new Date() - startTime elapsedTime <= clickTime? console.log("It's a click"): console.log(`It was held by ${elapsedTime} ms`) })
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button id='btn'>Hold: :)</button>

最后:您可以根據設置為被視為按住按鈕的時間來檢測按鈕是否被按住,然后您可以實現您的邏輯。

暫無
暫無

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

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