当一页上有多个带有滚动条的元素时(也许通过设置 CSS overflow-scroll
),键盘上的箭头键始终只滚动一个区域(这是一件好事)。似乎我用鼠标单击的最后一个带有滚动条的元素总是能够识别关键事件并滚动( example on Codepen )。
有没有办法找出哪个元素(上例中的 div
元素)具有键盘“焦点”(引号,因为它似乎没有获得焦点伪类,请参见上面的示例)?
最佳答案
您可以将 tabindex
添加到外部或滚动元素,然后使用 document.activeElement
window.addEventListener('keydown', e => {
let a = document.activeElement;
console.log(a);
})
.container {
display: flex;
}
.outer-left {
width: 200px;
height: 200px;
overflow-y: scroll;
}
.inner-left {
height: 500px;
background-color: red;
}
.outer-right {
width: 200px;
height: 200px;
overflow-y: scroll;
}
.inner-right {
height: 500px;
background-color: blue;
}
<div class="container">
<div class="outer-left" tabindex="1">
<div class="inner-left">
</div>
</div>
<div class="outer-right" tabindex="2">
<div class="inner-right">
</div>
</div>
</div>
关于javascript - 找出哪个滚动元素具有键盘焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50210960/