为了账号安全,请及时绑定邮箱和手机立即绑定

检测网页上的用户输入(击键或输入的事件处理)

检测网页上的用户输入(击键或输入的事件处理)

眼眸繁星 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 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信