jQuery scrollTo - 在窗口中垂直居中 Div [英] jQuery scrollTo - Center Div in Window Vertically

查看:43
本文介绍了jQuery scrollTo - 在窗口中垂直居中 Div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个使用页面顶部固定菜单的网站.

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

当一个链接被点击时,它应该垂直滚动,使目标 div 的中心与窗口的垂直中心对齐,偏移标题的高度.- 这很重要,这样无论显示器的分辨率如何,div 都居中

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

我正在使用 jQuery 和 scrollTo,但无法计算出所需的数学运算.

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

这是我的尝试:

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

推荐答案

最终想通了.只是对数学很笨.使用固定的页眉和页脚偏移也适用于所有分辨率.

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

这篇关于jQuery scrollTo - 在窗口中垂直居中 Div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆