情况:有一个带有
overflow: auto
的固定高度父 div 和足够高度的子“line-item”div 来触发滚动条的存在。这些子 div 中的每一个都有 tabindex=-1,因此可以以编程方式聚焦。
当这些子 div 中的任何一个以编程方式聚焦时,浏览器(在本例中为 Chrome 55)的默认行为似乎是滚动父 div 以使新聚焦的子 div 居中。有什么办法可以阻止这种行为吗?
是和不是。没有办法阻止父元素滚动到焦点元素(据我所知)。但是,您可以通过将父元素滚动回顶部来撤消滚动。如果做得正确,用户不会注意到它。
为此,只要您以编程方式聚焦某个元素,请检索聚焦元素的父节点的当前滚动偏移量,并将
scrollTop
设置为该偏移量。
var children = document.getElementsByClassName('child')
for (var i = 0; i < children.length; i++) {
children[i].addEventListener('click', function (e) {
e.preventDefault
var focused = document.getElementById('focus')
var focusedParent = focused.parentNode
var savedOffset = focusedParent.scrollTop
focused.focus();
focused.parentNode.scrollTop = savedOffset;
})
}
.parent {
height: 300px;
overflow: auto;
}
.child {
height: 50px;
background-color: gray;
border-bottom: 1px solid black;
color: white;
box-sizing: border-box;
text-align: center;
line-height: 50px;
font-family: Arial;
}
<div class="parent">
<div class="child" tabIndex="-1">1</div>
<div class="child" tabIndex="-1">2</div>
<div class="child" tabIndex="-1">3</div>
<div class="child" tabIndex="-1">4</div>
<div class="child" tabIndex="-1">5</div>
<div class="child" tabIndex="-1">6</div>
<div class="child" tabIndex="-1">7</div>
<div class="child" tabIndex="-1">8</div>
<div class="child" tabIndex="-1" id="focus">9</div>
<div class="child" tabIndex="-1">10</div>
</div>
这是 Codepen 上的工作演示。
回答我自己的问题:截至 2021 年,所有常青浏览器都支持例如
element.focus({ preventScroll: true })
作为一个选项。