Plain JavaScript - ScrollIntoView inside Div

2020-07-13 10:14发布

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 ScrollIntoView provides, but for a specified parent (only this parent should scroll).
Additionally it is not possible for me to use any 3rd party libraries.


I am not quite sure on how to approach this problem, as I do very limited JavaScript development. Is there someone that could help me out?


I found this code that would do exactly what I need, but unfortunately it requires JQuery and I was not able to translate it to plain JavaScript.

3条回答
我欲成王,谁敢阻挡
2楼-- · 2020-07-13 10:52

You can do some easy stuff like:

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

Basically window.location.href should help you.

查看更多
手持菜刀,她持情操
3楼-- · 2020-07-13 10:54

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';
查看更多
相关推荐>>
4楼-- · 2020-07-13 11:00

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/

查看更多
登录 后发表回答