我有一個帶有多個按鈕的頁面。當我按空格鍵時,它會運行該功能。但是如果我按下按鈕 x 并再次按下空格鍵,它會運行按鈕 x 的功能。我該如何解決?
const x = str => console.log(str);
const spacebar = () => console.log('space');
document.addEventListener("keydown", function(event) {
if (event.key === '1') {
x(event.key);
}
if (event.key === ' ') {
spacebar();
}
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
uj5u.com熱心網友回復:
因為您的代碼在 keydown 上運行,而空格鍵按 keyup 上的 x 按鈕。您可以將焦點從檔案上的任何其他內容移開,以確保空間不會做其他事情。
const x = str => console.log(str);
const spacebar = () => console.log('space');
document.addEventListener("keydown", function(event) {
if (event.key === '1') {
x(event.key);
}
if (event.key === ' ') {
spacebar();
document.activeElement.blur(); // I just added this line
}
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
uj5u.com熱心網友回復:
使用preventDefault()以防止默認的瀏覽器的行為。因為您的 x 按鈕具有焦點,所以在例如 Google Chrome 中按空格時它會再次運行。
const x = str => console.log(str);
const spacebar = () => console.log('space');
document.addEventListener("keydown", function(event) {
if (event.key === '1') {
x(event.key);
}
if (event.key === ' ') {
event.preventDefault();
spacebar();
}
})
<button onclick="x('button')"> x </button>
<button onclick="spacebar()"> spacebar </button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/341321.html
標籤:javascript html css 事件
上一篇:訪問輸入欄位Puppetier
下一篇:使用函式而不是多個ifelse
