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

Find out which scroll element has keyboard focus

当一页上有多个带有滚动条的元素时(可能通过设置 CSS overflow-scroll),键盘上的箭头键总是只滚动一个区域(这是一件好事)。似乎我用鼠标单击的最后一个带有滚动条的元素总是识别关键事件并滚动(example on Codepen)。

有没有办法找出哪个元素(上例中的 div 元素)具有键盘 "focus"(引用因为它似乎没有获得焦点伪类,请参见示例以上)?

您可以将 tabindex 添加到 outer 或滚动元素,然后使用 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>

您可以将 tabindex="0" 添加到 div。

https://codepen.io/gezzasa/pen/QrOdqX