简体   繁体   English

有没有办法防止父容器在子节点聚焦时滚动?

[英]Is there a way to prevent a parent container from scrolling when a child node is focused?

Situation: there is a fixed-height parent div with overflow: auto and enough child "line-item" divs of sufficient height to trigger the presence of scrollbars. 情况:有一个固定高度的父div, overflow: auto和足够高的子“line-item”div足以触发滚动条的存在。 Each of these child divs has tabindex=-1 so can be programmatically focused. 这些子div中的每一个都具有tabindex = -1,因此可以以编程方式聚焦。

When any of these child divs is programmatically focused, the default behavior of the browser (in this case, Chrome 55) seems to be to scroll the parent div to center the newly-focused child. 当这些子div中的任何一个以编程方式聚焦时,浏览器的默认行为(在这种情况下,Chrome 55)似乎是滚动父div以使新聚焦的子中心居中。 Is there any way to prevent this behavior? 有什么方法可以防止这种行为吗?

Yes and no. 是的,不是。 There is not a way to prevent the parent element from scrolling to the focused element (that I know of). 没有办法阻止父元素滚动到聚焦元素(我知道)。 However, you can undo the scrolling by scrolling the parent element back to the top. 但是,您可以通过将父元素滚动回顶部来撤消滚动。 Done correctly, it won't be noticeable to the user. 如果操作正确,则用户不会注意到。

To do this, anytime you programmatically focus an element, retrieve the current scroll offset of the focused element's parent node and set scrollTop to that offset. 为此,只要您以编程方式聚焦元素,检索焦点元素的父节点的当前滚动偏移量,并将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> 

Here's the working demo on Codepen . 这是Codepen上的工作演示。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM