javascript - 找出哪个滚动元素具有键盘焦点

标签 javascript html css overflow keyboard-events

当一页上有多个带有滚动条的元素时(也许通过设置 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/

相关文章:

javascript - 我可以在 mocha 输出中隐藏失败详细信息吗?

javascript - 如何使用鼠标单击并拖动来放大D3

javascript - Rails 上带有 selenium 的 chromedriver

javascript - 使用 React JS 时输入类型文本值未更新

javascript - 更新 jquery 关联数组值

html - Bootstrap Carousel li元素事件类不起作用

html - 两个相邻的 div,没有固定宽度的元素

javascript - 将 div 调整为容器中最大可能的正方形

javascript - jQuery:淡出,改变背景图像,然后淡入

html - 由于位置为 :absolute which is outside of the page 的 DIV,禁用水平滚动条