javascript jQuery scrollTo - 在窗口中垂直居中 Div

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10889983/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 11:23:09  来源:igfitidea点击:

jQuery scrollTo - Center Div in Window Vertically

javascriptjqueryhtmlscrollcenter

提问by jwg2s

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

单击链接时,它应该垂直滚动,以便该目标 div 的中心与窗口的垂直中心对齐,偏移标题的高度。- 这非常重要,因此无论显示器的分辨率如何,div 都居中

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

我正在使用 jQuery 和 scrollTo,但无法弄清楚这需要什么数学。

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);
}

采纳答案by jwg2s

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);
}

回答by Dips

I have done a simple jquery. I think that might help what you are looking for.

我做了一个简单的jquery。我认为这可能对您正在寻找的有所帮助。

Please see demo

请看演示

The target divstay vertically centre offset header.

目标div保持垂直居中偏移标题。