gpt4 book ai didi

jquery - 滚动到 DIV 的垂直中间

转载 作者:行者123 更新时间:2023-12-01 01:15:13 26 4
gpt4 key购买 nike

我有一个单页设计,其中有一些 div 在一起。当我单击菜单链接(“3”)时,我想滚动到 div #3,它应该位于屏幕的垂直中间。

我尝试过:

$('#go').click(function() {
$('html,body').animate({ scrollTop: $(.box).offset().top - ( $(window).height() -
$(.box).outerHeight(true) ) / 2 }, 200);
});

这不起作用。我忘记了什么?

这是一个 fiddle :http://jsfiddle.net/herrfischerhamburg/7CVtm/1/

最佳答案

您需要将选择器括在引号中:$('.box')

$('#go').click(function (e) {
e.preventDefault();
var $box = $('.box').eq(2); // select the third box

$('html, body').animate({
scrollTop: $box.offset().top - ($(window).height() - $box.outerHeight(true)) / 2
}, 200);
});

Updated fiddle

关于jquery - 滚动到 DIV 的垂直中间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20515095/

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