JavaScript - 将溢出的列表元素滚动到视图中

时间:2016-10-22 01:49:01

标签: javascript html css reactjs

所以你有一个很长的可滚动列表,并希望将特定的DOM元素滚动到视图中:

我已经想出了一个我想与你们分享的解决方案,我希望它对一些人有所帮助! (此质量保证理念直接来自SO) 我已经在SO上看到了一些较小的JS技巧,并在下面提出了这个功能:

1 个答案:

答案 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 中的最后一个可见位置(意味着位置)在模态容器的底部正上方

以下是我想指出的一些事项:

  • getComputedStyle(以及getPropertyValue)允许我们通过删除使用offsetHeight
  • parseInt的第二个参数是重要的,我刚发现的东西 - 这里它确保结果在10的基础上(如果无法解析则为NaN)
  • querySelector抓取与css选择器匹配的第一个子元素 - 在这种情况下,我用它来测量单个列表项的视觉高度,以确保elementToView完全适合作为最后一个可见列表项
  • 最后,我们要将elementToView滚动到容器的距离减去列表顶部的列表项(以便滚动列表项以查看附加到容器的底部)。如果您希望项目位于列表顶部,或者可能位于中间
  • ,则可以在此处进行调整
  • 另外,如果您不确定 let 关键字,请参阅this

我希望这有帮助!