Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
581 views
in Technique[技术] by (71.8m points)

javascript - jQuery scrollTo - Center Div in Window Vertically

I have a site that uses a fixed menu on the top of the page.

When a link is clicked, it should scroll vertically so that the center of that target div aligns with the vertical center of the window, offset by the height of the header. - this is very important so that the div is centered no matter what the resolution of the monitor is

I'm using jQuery and scrollTo, but can't figure out the math needed for this.

Here's my attempt:

function scrollTo(target) {
var offset;
var scrollSpeed = 600;

if (viewport()["width"] > 767 && !jQuery.browser.mobile) {
    // Offset anchor location and offset navigation bar if navigation is fixed
    offset = $(target).offset().top - document.getElementById('navigation').clientHeight;
} else {
    // Offset anchor location only since navigation bar is now static
    offset = $(target).offset().top;
}

    $('html, body').animate({scrollTop:offset}, scrollSpeed);
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Eventually figured it out. Was just being dumb with the math. Offset with the fixed header and footer as well, works for all resolutions.

    // scrollTo: Smooth scrolls to target id
function scrollTo(target) {
    var offset;
    var scrollSpeed = 600;
        var wheight = $(window).height();
        //var targetname = target;
        //var windowheight = $(window).height();
        //var pagecenterH = windowheight/2;
        //var targetheight = document.getElementById(targetname).offsetHeight;

    if (viewport()["width"] > 767 && !jQuery.browser.mobile) {
        // Offset anchor location and offset navigation bar if navigation is fixed
        //offset = $(target).offset().top - document.getElementById('navigation').clientHeight;
                offset = $(target).offset().top - $(window).height() / 2 + document.getElementById('navigation').clientHeight + document.getElementById('footer').clientHeight;
    } else {
        // Offset anchor location only since navigation bar is now static
        offset = $(target).offset().top;
    }

    $('html, body').animate({scrollTop:offset}, scrollSpeed);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...