4 回答

TA貢獻1847條經驗 獲得超7個贊
您需要收聽該input事件,因為正如您所說change,僅在輸入失去焦點后觸發,這不是您想要的。您還需要只處理一次事件。
document.getElementById("test-area").addEventListener("input", () => {
startTimer(1);
}, {once: true});
請注意,這會在觸發事件處理程序后刪除它。如果您需要再次運行它,您將不得不再次注冊該事件。也許在您的計時器回調中。

TA貢獻1785條經驗 獲得超8個贊
一些解決方案:
變體 1
只需創建一個標志:
var timerStarted = false; // Was the timer started?
document.getElementById("test-area").oninput = function () {
if(timerStarted) return; // If timer was started - do nothing
startTimer(1); // Else - start the timer
timerStarted = true; // Remember what we've started the timer
};
變體 2
(有點短)
document.getElementById("test-area").addEventListener("input", function () {
startTimer(1);
}, {once: true}); // Good thing about addEventListener
// With this it will run the event only single time
更多信息:https ://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener

TA貢獻1779條經驗 獲得超6個贊
你試過 onfocus 嗎?它不完全是他們開始打字的時間,但它確實有效。另一種選擇是您使用 onInput 并在時鐘啟動功能上將布爾值 -isRunning - 更改為 true。然后放一個 if (isRunning) 返回。就像是:
function start() {
if(isRunning) return;
isRunning = true;
}
然后在停止 onChange 時將布爾值更改為 false

TA貢獻1797條經驗 獲得超4個贊
可以用 JQuery 嗎?如果是這樣,它有一個方法 .one() 將只執行一次函數。然后您可以自由使用 keydown/keyup 事件處理程序。例如。
<script>
$(document).ready(function(){
$("#test-area").one("keydown", function() {
alert("hey");
});
});
</script>
添加回答
舉報