简体   繁体   中英

JavaScript - Scroll down to element

You can scroll to an element using a url with a hashtag and the elements ID:

window.location.href = "#ID"

This will scrol so that the top of the element is at the top of the browser. How would I scroll to an element so that it's vertically centered?

you can scroll up right after the navigation happens:

addEventListener("hashchange", function(){
    setTimeout(function(){ 
          document[
             document.documentElement.scrollTop ? 
             "documentElement":
             "body"
          ].scrollTop-= (innerHeight/2.1);
     }, 1); 
}, false);

this will cause the focused element to appear half-way up the screen, vertically centered. the 2.1 causes it to scroll just under half the screen, since there will be some room at the top already. you can adjust the ".1" to match your desired effect (baseline, middle, etc).

obligatory fiddle link: http://jsfiddle.net/ckhafLzq/2/

This is what I have achieved:

function centerScroll(element) {
    if (!(element instanceof Element)) {
        throw new TypeError("Element expected");
    }

    var bodyRect = document.body.getBoundingClientRect();
    var elementRect = element.getBoundingClientRect();

    var left = elementRect.left - bodyRect.left;
    var top = elementRect.top - bodyRect.top;

    var windowWidth = window.innerWidth;
    var windowHeight = window.innerHeight;

    var elementWidth = element.offsetWidth;
    var elementHeight = element.offsetHeight;

    var x = left - Math.max(0, (windowWidth - elementWidth) / 2);
    var y = top - Math.max(0, (windowHeight - elementHeight) / 2);

    window.scrollTo(x, y);

    return [x, y];
}

No, there's no built-in way, you'd have to write that yourself:

function center_element_vertically(elt) {
    var rect = elt.getBoundingClientRect();
    window.scrollTo(0, rect.top + window.pageYOffset - 
        (window.innerHeight - rect.height)/2);
}

Alternatives without writing your own code: you could scroll so that the element was at the bottom by passing false to scrollIntoView , or scroll only if the element is not already visible by calling scrollIntoViewIfNeeded , available only in Chrome AFAIK.

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