2017-07-31 45 views
0

我有要求滚动某个div内的某个元素(而不是直接子)到视图中。Plain JavaScript - ScrollIntoView Div


基本上我需要相同的功能ScrollIntoView提供,但对于一个指定的父(只此父应滚动)。
此外,我不可能使用任何第三方库。


我不太清楚如何解决这个问题,因为我的JavaScript开发非常有限。有人可以帮助我吗?


我发现this code会做正是我需要的,但不幸的是它需要jQuery和我不能将它翻译成普通的JavaScript。

回答

1

我想我有一个开始。当你考虑这个问题时,你会考虑让孩子进入父母的可见区域。一种天真的做法是使用页面上父子位置相对于页面上孩子的位置。然后考虑父母的滚动。继承人可能的实现。

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 
    } 


} 

只是通过像这样的家长和子节点:

scrollParentToChild(parentElement, childElement) 

添加使用该功能的主要元素,甚至嵌套元素

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

+0

谢谢,这帮了我一个开始! – JDC

0

你可以做一些简单的东西,如:

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

基本上window.location.href应该帮助你。

+0

上者均基于演示“id”的想法是你可以使用GETURL参数 - 有点高级。只需尝试window.location.href =“mydiv”。 –

+0

这不会滚动整个页面吗?我编辑了这个问题。对我来说,只有指定的父卷轴才是重要的。 – JDC

+0

好吧,现在我明白了 - 只需跳到父母身边就是您的要求。然后你需要额外的CSS。 –

0

这个功能可以通过几个步骤来实现。 首先,你使用childElement.getBoundingClientRect(); 将返回下列值

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

然后,只需按左上角的值到保持子元素positionabsolute父元素位置的子元素得到孩子的位置。父元素的position必须是relative类型才能正确放置孩子并获得ScrollIntoView的效果。

childElement.style.position = 'absolute'; 
childElement.style.top = 'value in px'; 
childElement.style.left = 'value in px';