繁体   English   中英

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

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

关联

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

理想情况下,整个元素应该是可见的,甚至在页面上居中。

在检查源代码时,插件如何决定停止滚动的时间并不是很明显。

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

我最终从头开始编写了一个小型轻量级实现。 它假定要滚动到的元素是可滚动容器的直接子元素。 它适用于 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);
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM