页面加载时滚动到特定的div

31

我正在尝试找出如何在页面加载后让页面自动滚动到特定的

。 我已经尝试使用jQuery滚动函数,但无法使其正常工作。 有什么建议吗?

以下是我目前尝试过的:

jQuery(function() {
jQuery(window).scrollTop(jQuery('.container').offset().top);
});
3个回答

76
你可以使用 .animate() 方法来实现这个效果:
$(document).ready(function () {
    // Handler for .ready() called.
    $('html, body').animate({
        scrollTop: $('#what').offset().top
    }, 'slow');
});
  • 这将平滑滚动到带有ID what 的div元素

FIDDLE


这个能动态完成吗?我想在查询字符串中发送div的名称,例如:show.aspx?divToScrollTo=SecondDiv。 - John
当然可以做到。只需从查询字符串中获取div id,并在页面加载时将其传递给上面的代码,如:$('#' + divToScrollTo).offset().top,其中divToScrollTo是我们存储查询字符串值的js变量。 - palaѕн
我想补充一点,如果你对最终的位置不是完全满意,你可以添加(向下)或减去(向上)你想要移动的像素数量。 - tomashauser

2
$(document).ready(function(){
    $("html, body").animate({ 
        scrollTop: $('.sb-menu').offset().top 
    }, 1000);
});

2

首先,您需要调用文件:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">

这里的id是“scroll”。 以下代码很有帮助:

<html>
<head>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function () {
    // Handler for .ready() called.
    $('html, body').animate({
        scrollTop: $('#scroll').offset().top
    }, 'slow');
});

</script>

</head>
<body>

<div id="scroll"></div>

</body>
</html>

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