所以你有一个很长的可滚动列表,并希望将特定的DOM元素滚动到视图中:
我已经想出了一个我想与你们分享的解决方案,我希望它对一些人有所帮助! (此质量保证理念直接来自SO) 我已经在SO上看到了一些较小的JS技巧,并在下面提出了这个功能:
答案 0 :(得分:1)
/**
* scroll an overflowed list so that the elementToView is visible
*
* @param {<NodeList item>} elementToView list element to make visible
* @param {<NodeList item>} elementContainer element containing the elementToView
* @param {<NodeList item>} listElement actual list (<ul>?) element to scroll (could be the same as container)
*
*
*/
function scrollList(elementToView, elementContainer, listElement) {
let containerHeight, topPos, listItem, temp = null
if (typeof window !== 'undefined' && elementToView && elementContainer && listElement) {
temp = window.getComputedStyle(elementContainer, null).getPropertyValue('padding-top')
temp = parseInt(temp, 10) + parseInt(window.getComputedStyle(elementContainer, null).getPropertyValue('padding-bottom'), 10)
// temp holds the top and bottom padding
// usable space is the offsetHeight - padding
containerHeight = elementContainer.offsetHeight - temp
// amount of pixels away from the top of the container
topPos = elementToView.offsetTop
if (!containerHeight || !topPos) return false
// get the height of a list item in the list to scroll
listItem = listElement.querySelector('li:first-of-type').offsetHeight
// actually do the scrolling now
// scroll the top of the list to show the elementToView on the bottom (as the last visible element in the list)
listElement.scrollTop = (topPos - (containerHeight - listItem))
}
}
以下是该函数的一个示例用法:
let focusElement = document.getElementsByClassName('focus')[0]
let containerElement = document.getElementsByClassName('modal')[0]
let listElement = document.getElementsByClassName('chapter-list')[0]
// let's check if any selection index has changed, and then scroll to the correct
// positions to make sure the selected elements are in view
if (chapterlistSelectionIndex !== prevState.chapterlistSelectionIndex) {
scrollList(focusElement, containerElement, listElement)
}
这将使用焦点类获取DOM元素(li项)并将其滚动到 chapter-list 中的最后一个可见位置(意味着位置)在模态容器的底部正上方
以下是我想指出的一些事项:
我希望这有帮助!