Plain JavaScript - ScrollIntoView inside Div

前端 未结 3 484
滥情空心
滥情空心 2021-01-03 03:28

I have the requirement to scroll a certain element inside a div (not a direct child) into view.


Basically I need the same functionality as Sc

3条回答
  •  孤独总比滥情好
    2021-01-03 04:28

    I think I have a start for you. When you think about this problem you think about getting the child div into the viewable area of the parent. One naive way is to use the child position on the page relative to the parent's position on the page. Then taking into account the scroll of the parent. Heres a possible implementation.

    function scrollParentToChild(parent, child) {
    
      // Where is the parent on page
      var parentRect = parent.getBoundingClientRect();
      // What can you see?
      var parentViewableArea = {
        height: parent.clientHeight,
        width: parent.clientWidth
      };
    
      // Where is the child
      var childRect = child.getBoundingClientRect();
      // Is the child viewable?
      var isViewable = (childRect.top >= parentRect.top) && (childRect.top <= parentRect.top + parentViewableArea.height);
    
      // if you can't see the child try to scroll parent
      if (!isViewable) {
        // scroll by offset relative to parent
        parent.scrollTop = (childRect.top + parent.scrollTop) - parentRect.top
      }
    
    
    }
    

    Just pass it the parent and the child node like this:

    scrollParentToChild(parentElement, childElement)
    

    Added a demo using this function on the main element and even nested elements

    https://jsfiddle.net/nex1oa9a/1/

提交回复
热议问题