Plain JavaScript - ScrollIntoView inside Div

前端 未结 3 458
滥情空心
滥情空心 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:03

    You can do some easy stuff like:

    function customScroll(id) {
        window.location.href = "#mydiv"+id;
    }
    

    Basically window.location.href should help you.

    0 讨论(0)
  • 2021-01-03 04:05

    This functionality can be achieved in some few steps. First you get the position of the child using childElement.getBoundingClientRect(); which will return the following values

    bottom : val
    height: val
    left: val
    right: val
    top: val
    width: val
    

    Then just position the child element according to the top left values into the parent element keeping child elements position as absolute. The parent Element's position must be relative type to place the child properly and get the effect of ScrollIntoView.

    childElement.style.position = 'absolute';
    childElement.style.top = 'value in px';
    childElement.style.left = 'value in px';
    
    0 讨论(0)
  • 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/

    0 讨论(0)
提交回复
热议问题