亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

檢測網頁上的用戶輸入(擊鍵或輸入的事件處理)

檢測網頁上的用戶輸入(擊鍵或輸入的事件處理)

眼眸繁星 2023-12-14 15:44:13
我正在創建一個基本的 Chrome 擴展,當用戶在網頁上的任何位置鍵入時,它會發送消息提醒。但是,我不確定如何實現這一點,我考慮過使用keyUp和keyDown事件,但只有當事件正在監視特定字段時我才成功,而目標是檢測用戶可以鍵入的任何字段上的文本。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);}達到預期結果的最佳方法是什么?請記住,我試圖在用戶在網頁上輸入文本或用戶單擊文本字段內部開始輸入時觸發此 chrome 擴展。僅當用戶在文本字段中沒有文本且文本字段未處于活動狀態時,chrome 擴展才應消失(否則,如果文本字段中有文本,則保留擴展)。
查看完整描述

1 回答

?
Cats萌萌

TA貢獻1805條經驗 獲得超9個贊

一種選擇是將事件偵聽器添加到 html 元素:


document.querySelector('html').addEventListener('keypress', () => {

  console.log('asd')

});

另一種選擇是循環遍歷用戶可以輸入的所有字段:


document.querySelectorAll('input').forEach(inp => {

  inp.addEventListener('keypress', () => {console.log('asd')})

});


查看完整回答
反對 回復 2023-12-14
  • 1 回答
  • 0 關注
  • 172 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號