gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 03:53:20 25 4
gpt4 key购买 nike

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

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

我正在使用 jQuery 和 scrollTo,但无法弄清楚为此需要的数学知识。

这是我的尝试:

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

最佳答案

终于明白了。只是对数学很愚蠢。偏移固定的页眉和页脚,适用于所有分辨率。

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

关于javascript - jQuery scrollTo - 在窗口中垂直居中 Div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10889983/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com