jQuery的scrollTop,如何滚动到带有id的div?

36

这是我现有的代码:

$(document).ready(function() {
    $('.abouta').click(function(){
        $('html, body').animate({scrollTop:308}, 'slow');
        return false;
    });
    $('.portfolioa').click(function(){
        $('html, body').animate({scrollTop:708}, 'slow');
        return false;
    });
    $('.contacta').click(function(){
        $('html, body').animate({scrollTop:1108}, 'slow');
        return false;
    });
});

当你点击一个链接,比如“about”,它会滚动到页面的特定部分。我更希望使用scrollTo

标签的id来实现,这样如果我更改了填充等内容,就不必再更改scrollTo的位置了。有没有办法实现?

6个回答

110
代替
$('html, body').animate({scrollTop:xxx}, 'slow');
使用
$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');

这将返回您所选择的任何元素的绝对顶部位置,例如#div_id


6
我很惊讶已经有这么长时间没有人评论了 - 目前的问题实际上是在寻找 .offset() 而不是 .position() 作为解决方案,对吗?目标 div 可以位于页面的任何位置,而 .position() 返回相对于其容器框的顶部偏移量。因此,如果目标 div 是其父元素的第一个子元素,则上面的代码会将您带到文档的顶部。或者我有什么遗漏的地方吗? - sameers
谢谢Sameers,这正是我遇到的问题。.offset()很好用。 - Dan382

2

我的解决方案如下:

document.getElementById("agent_details").scrollIntoView();

我需要将页面滚动到 HTML 表格的特定行。这可以通过行 ID 属性实现。 - Atiq Baqi

0

使用这个:

$('html').animate({ scrollTop: $("#yourDiv").offset().top-100 }, "slow");

0

试试这个:

$('html, body').animate({scrollTop:$('#xxx').position().top}, 'slow');
$('#xxx').focus();

0
尝试这个。
    $('#div_id').animate({scrollTop:0}, '500', 'swing');

-2

如果你想滚动某个 div,可以使用该 div 的 id,而不是 'html, body'

$('html, body').animate(...

使用

$('#mydivid').animate(...

3
дёҚпјҢ$('#div').animate({scrollTop:$('#div').position().top}, 'slow'); еңЁChrome 23дёӯдёҚиғҪжӯЈеёёе·ҘдҪңгҖӮжӣҙеҘҪзҡ„ж–№ејҸжҳҜдҪҝз”Ё$('html, body').animate({scrollTop:$('#div_id').position().top}, 'slow');гҖӮ - bicycle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接