gpt4 book ai didi

javascript - 是否可以触发不在 input 或 textarea 标签中的 javascript keypress 事件?

转载 作者:行者123 更新时间:2023-12-01 16:00:44 24 4
gpt4 key购买 nike

我想知道您是否可以触发 javacript keypress 事件,但不能在输入输出 textarea 标记内触发?

我想要实现的是,当用户在页面上的任何位置按下任何键时,都会显示警报:您按下了一个键。

这是我的代码:http://codepen.io/willydev/pen/LkZAob

function pushbtn(event){
var x = event.keyCode;
alert("You pressed"+x)
}

我不确定要使用事件监听器或我应该把它放在哪里。

最佳答案

当然可以,只需委托(delegate) keypress document 的事件处理程序:

function pushbtn(event) {

// retrieving the keyCode of the pressed key:
var keycode = event.keyCode,

// finding which letter was generated, using
// String.fromCharCode():
key = String.fromCharCode(keycode);
console.log('You pressed ' + key + ' (keyCode: ' + keycode + ').');
}

document.addEventListener('keypress', pushbtn);
body,
html {
height: 100vh;
width: 100vw;
margin: 0;
background-color: #f00;
}


如果您希望排除那些 keypress <input> 内触发的事件或 <textarea>要素:

function pushbtn(event) {
var keycode = event.keyCode,
key = String.fromCharCode(keycode),

// finding the element on which the event
// was originally fired:
source = event.target,

// an Array of element-types upon which
// the function should not fire (to prevent
// interfering needlessly with the UI and
// user-expectations):
exclude = ['input', 'textarea'];

// finding the element-type (tagName) of the element
// upon which the event was fired, converting it to
// a lower-case string and then looking in the Array
// of excluded elements to see if the element is held
// within (-1 indicates the string was not found within
// the Array):
if (exclude.indexOf(source.tagName.toLowerCase()) === -1) {
console.log('You pressed ' + key + ' (keyCode: ' + keycode + ').');
}
return;
}

document.addEventListener('keypress', pushbtn);
body,
html {
height: 100vh;
width: 100vw;
margin: 0;
background-color: #f00;
}
input,
textarea {
display: block;
width: 30%;
box-sizing: border-box;
margin: 0.5em 0 0 1em;
}
<input />
<textarea></textarea>

关于javascript - 是否可以触发不在 input 或 textarea 标签中的 javascript keypress 事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38414646/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com