Plain JavaScript - ScrollIntoView inside Div

前端 未结 3 488
滥情空心
滥情空心 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: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';
    

提交回复
热议问题