纯 JavaScript - Div 内的 ScrollIntoView [英] Plain JavaScript - ScrollIntoView inside Div

查看:48
本文介绍了纯 JavaScript - Div 内的 ScrollIntoView的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要将 div 中的某个元素(不是直接子元素)滚动到视图中.

I have the requirement to scroll a certain element inside a div (not a direct child) into view.

基本上我需要与 ScrollIntoView 提供的功能相同的功能,但对于指定的父级 (只有这个父级应该滚动).
此外,我无法使用任何 3rd 方库.

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.

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

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?

我发现 这段代码完全可以我需要什么,但不幸的是它需要 JQuery,我无法将其转换为纯 JavaScript.

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.

推荐答案

我想我有一个开始.当您考虑这个问题时,您会考虑将子 div 放入父级的可视区域.一种天真的方法是使用页面上相对于父级在页面上的位置的子级位置.然后考虑到父级的滚动.这是一个可能的实现.

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. Here's 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.bottom <= parentRect.top + parentViewableArea.height);

  // if you can't see the child try to scroll parent
  if (!isViewable) {
        // Should we scroll using top or bottom? Find the smaller ABS adjustment
        const scrollTop = childRect.top - parentRect.top;
        const scrollBot = childRect.bottom - parentRect.bottom;
        if (Math.abs(scrollTop) < Math.abs(scrollBot)) {
            // we're near the top of the list
            parent.scrollTop += scrollTop;
        } else {
            // we're near the bottom of the list
            parent.scrollTop += scrollBot;
        }
  }

}

只需像这样将父节点和子节点传递给它:

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/

这篇关于纯 JavaScript - Div 内的 ScrollIntoView的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆