您如何制作特定的按键?当按下该按键时,屏幕上的一个框/所选内容会亮起吗?例如,如果我按M,我希望中间的框亮起
答案 0 :(得分:1)
在这里,我们列出按键,并查找实现该类的项目并添加突出显示。 (注意:如果要多个,请使用querySelectorAll和forEach)
const findDiv = (key) => {
let className = `.key${key}`;
return document.querySelector(className);
};
document.addEventListener('keydown', (e) => {
let div = findDiv(e.key);
if(div) div.classList.add('highlight');
});
document.addEventListener('keyup', (e) => {
document.querySelectorAll('.item').forEach(d => d.classList.remove('highlight'));
});
.highlight {
background-color: yellow;
}
<div class="grid-container">
<div class="item keyShift">1</div>
<div class="item keyArrowDown">2</div>
<div class="item keyArrowUp">3</div>
<div class="item keyArrowLeft">4</div>
<div class="item keyArrowRight">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
</div>