如何使用 onClick 在 Javascript 中触发键盘事件?
How to fire keyboard events in Javascript using onClick?
我有一个在按下 KeyD 时调用的现有函数。
我想在单击某个按钮时立即触发 KeyD 事件(无需实际按下键盘上的 keyD)。
Javascript可以吗?
您必须实施 dispatchEvent。
let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd'}));
}
<input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>
您可以使用 javascript 中的 onkeypress() 函数,它会在每次按键时触发。
是的,有可能
button.addEventListener('click', function(){
let keydown = new KeyboardEvent('keydown', {key: 'a', code: 'KeyA', keyCode: 65});
element.dispatchEvent(keydown); // element is the one you want to trigger the event
});
KeyboardEvent
的构造请阅读https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
您需要创建一个 new KeyboardEvent
,并为 KeyboardEventInit
字典提供一个 key
,这是第二个参数。
然后使用dispatchEvent
触发元素上的事件。
let elem = document.querySelector("input");
elem.addEventListener("keypress", (e) => {
if(e.key === "d"){
keyDPressed();
}
});
elem.addEventListener("click", (e) => {
let eve = new KeyboardEvent('keypress',{ key : "d"})
e.target.dispatchEvent(eve);
});
function keyDPressed(e) { //function that gets called when key D is pressed
console.log("d was pressed");
}
<input value="Click here" type="button">
我有一个在按下 KeyD 时调用的现有函数。
我想在单击某个按钮时立即触发 KeyD 事件(无需实际按下键盘上的 keyD)。
Javascript可以吗?
您必须实施 dispatchEvent。
let element = document.querySelector('input');
element.onkeydown = e => alert(e.key);
changeValButton.onclick = () => element.value += "a";
dispatchButton.onclick = () => {
element.dispatchEvent(new KeyboardEvent('keydown', {'key': 'd'}));
}
<input/>
<button id="dispatchButton">Press to dispatch event </button>
<button id="changeValButton">Press to change value </button>
您可以使用 javascript 中的 onkeypress() 函数,它会在每次按键时触发。
是的,有可能
button.addEventListener('click', function(){
let keydown = new KeyboardEvent('keydown', {key: 'a', code: 'KeyA', keyCode: 65});
element.dispatchEvent(keydown); // element is the one you want to trigger the event
});
KeyboardEvent
的构造请阅读https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/KeyboardEvent
您需要创建一个 new KeyboardEvent
,并为 KeyboardEventInit
字典提供一个 key
,这是第二个参数。
然后使用dispatchEvent
触发元素上的事件。
let elem = document.querySelector("input");
elem.addEventListener("keypress", (e) => {
if(e.key === "d"){
keyDPressed();
}
});
elem.addEventListener("click", (e) => {
let eve = new KeyboardEvent('keypress',{ key : "d"})
e.target.dispatchEvent(eve);
});
function keyDPressed(e) { //function that gets called when key D is pressed
console.log("d was pressed");
}
<input value="Click here" type="button">