我需要将div(不是直接子节点)内的某个元素滚动到视图中.
基本上我需要与ScrollIntoView提供的功能相同,但是对于指定的父级(只有这个父级应该滚动).
此外,我无法使用任何第三方库.
我不太确定如何解决这个问题,因为我的JavaScript开发非常有限.有人可以帮助我吗?
我发现这个代码可以完全满足我的需要,但不幸的是它需要JQuery,我无法将其转换为纯JavaScript.
Jor*_*uro 13
我想我有一个开始.当您考虑这个问题时,您会考虑将子div放入父级的可视区域.一种天真的方式是使用页面上的子位置相对于父页在页面上的位置.然后考虑父母的滚动.继承人可能的实施.
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
}
}
Run Code Online (Sandbox Code Playgroud)
只需将父节点和子节点传递给它:
scrollParentToChild(parentElement, childElement)
Run Code Online (Sandbox Code Playgroud)
在主元素甚至嵌套元素上添加了使用此函数的演示
https://jsfiddle.net/nex1oa9a/1/
归档时间: |
|
查看次数: |
4883 次 |
最近记录: |