简体   繁体   中英

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

Link

When scrolling to an element that is located to the left of the current scroll position - only half of the element is visible.

Ideally, the whole element should be visible, and even centered on the page.

Upon checking the source code it is not immediately apparent how the plugin decides its time to stop the scrolling.

I know there is an offset setting that can be used to tweak the final scroll position but its only on the vertical axis and the size of the element will vary so I prefer not to change that setting each time but find a generic solution that automatically factors the size/position of the element to be scrolled to and centers it.

I ended up coding a small lightweight implementation from scratch. It assumes that the element to be scrolled to is a direct child of the scroll-able container. It works in a css transform-scale context because it does not depend on $.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);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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