修改jQuery.ScrollTo插件将元素滚动到页面中心(垂直/水平)或尽可能靠近中心

modify jQuery.ScrollTo plugin to scroll element to center of page (vertical/horizontal) or as close to center as possible

本文关键字:垂直 靠近 尽可能 水平 插件 ScrollTo jQuery 元素 滚动 修改      更新时间:2023-09-26

链接

当滚动到位于当前滚动位置左侧的元素时,只有一半的元素可见。

理想情况下,整个元素应该是可见的,甚至应该位于页面的中心。

在检查源代码后,插件如何决定停止滚动的时间还不清楚。

我知道有一个偏移设置可以用来调整最终滚动位置,但它只在垂直轴上,元素的大小会有所不同,所以我不想每次都更改该设置,而是找到一个通用的解决方案,自动调整要滚动到的元素的大小/位置并将其居中。

我最终从头开始编写了一个小型的轻量级实现。它假设要滚动到的元素是可滚动容器的直接子元素。它在css转换规模上下文中工作,因为它不依赖于$.position((

  function scrollIntoView($target) {
    var $parent = $target.parent(),
        top = parseInt($target.css('top')),
        left = parseInt($target.css('left')),
        height = $target.height(),
        width = $target.width(),
        bottom = top + height,
        right = left + width,
        xCenter = left + width / 2,
        yCenter = top + height / 2,
        sWidth = $parent[0].scrollWidth,
        sheight = $parent[0].scrollHeight,
        pWidth = $parent.width(),
        pHeight = $parent.height(),
        destLeft, destTop; // the destination values for scroll left and top of the parent
    // if element does not overfow on an axis, scroll to zero for that axis;
    destTop = bottom < pHeight ? 0 : bottom - pHeight / 2 - height / 4;
    destLeft = right < pWidth ? 0 : right - pWidth / 2 - width / 4;
    $parent.animate({ scrollLeft: destLeft, scrollTop: destTop }, 600);
}