我正在創(chuàng)建一個基本的 Chrome 擴展,當(dāng)用戶在網(wǎng)頁上的任何位置鍵入時,它會發(fā)送消息提醒。但是,我不確定如何實現(xiàn)這一點,我考慮過使用keyUp和keyDown事件,但只有當(dāng)事件正在監(jiān)視特定字段時我才成功,而目標(biāo)是檢測用戶可以鍵入的任何字段上的文本。let timer, timeoutVal = 1000; // time it takes to wait for user to stop typing in msconst status = document.getElementById('status');const typer = document.getElementById('typer');typer.addEventListener('keypress', handleKeyPress);typer.addEventListener('keyup', handleKeyUp);// when user is pressing down on keys, clear the timeoutfunction handleKeyPress(e) { window.clearTimeout(timer); status.innerHTML = 'Typing...';}// when the user has stopped pressing on keys, set the timeout// if the user presses on keys before the timeout is reached, then this timeout is canceledfunction handleKeyUp(e) { window.clearTimeout(timer); // prevent errant multiple timeouts from being generated timer = window.setTimeout(() => { status.innerHTML = 'Done'; }, timeoutVal);}達到預(yù)期結(jié)果的最佳方法是什么?請記住,我試圖在用戶在網(wǎng)頁上輸入文本或用戶單擊文本字段內(nèi)部開始輸入時觸發(fā)此 chrome 擴展。僅當(dāng)用戶在文本字段中沒有文本且文本字段未處于活動狀態(tài)時,chrome 擴展才應(yīng)消失(否則,如果文本字段中有文本,則保留擴展)。
檢測網(wǎng)頁上的用戶輸入(擊鍵或輸入的事件處理)
眼眸繁星
2023-12-14 15:44:13