如何使用jQuery滚动到div的顶部?

ACP*_*ACP 49 html jquery scroll scrolltop

我在div里面有一个gridview ..我想使用jquery从div底部滚动到div的顶部..任何建议..

<div id="GridDiv">
// gridview inside..
</div>
Run Code Online (Sandbox Code Playgroud)

我的gridview将自定义分页生成链接按钮...我将滚动到链接按钮底部的div顶部点击...

protected void Nav_OnClick(object sender, CommandEventArgs e)
    {
        LinkButton lb1 = (LinkButton)sender;
        //string s = lb1.ID;
        ScriptManager.RegisterClientScriptBlock(lb1, typeof(LinkButton), 
 "scroll", "javascript:document.getElementById('GridDiv').scrollTop = 0;", true);
Run Code Online (Sandbox Code Playgroud)

在javascript的位置,我将调用jquery函数...任何建议......

编辑:

完全像每个用户页面的Stackoverflow问题...当更改页面nos时,它滚动到顶部,效果流畅......我想实现这一点......

Gre*_*ews 177

以下是使用jquery可以执行的操作:

$('#A_ID').click(function (e) { //#A_ID is an example. Use the id of your Anchor
    $('html, body').animate({
        scrollTop: $('#DIV_ID').offset().top - 20 //#DIV_ID is an example. Use the id of your destination on the page
    }, 'slow');
});
Run Code Online (Sandbox Code Playgroud)

  • @citress硬编码值使得div的顶部不在浏览器窗口的顶部,纯粹是为了美观.(应该把它留下来) (5认同)
  • 真棒,你应该获得100个赞成票. (4认同)
  • 为什么硬编码值为" - 20"? (2认同)

小智 42

或者,为了减少代码,在您的点击内放置:

setTimeout(function(){ 

$('#DIV_ID').scrollTop(0);

}, 500);
Run Code Online (Sandbox Code Playgroud)

  • 语法不正确.应该是:`setTimeout(function(){$('#DIV_ID').scrollTop(0);},500);` (2认同)

Rat*_*bit 5

特别感谢斯多葛派

   $("#miscCategory").animate({scrollTop: $("#miscCategory").offset().top});
Run Code Online (Sandbox Code Playgroud)


Ate*_*ral 3

你可以只使用:

<div id="GridDiv">
// gridview inside...
</div>

<a href="#GridDiv">Scroll to top</a>
Run Code Online (Sandbox Code Playgroud)

  • +1对于用户问题的技术上出色的解决方案......但对于任何寻求实际问题答案的人来说完全没有用。(锚点并不能解决我的问题,我需要使用 javascript 将屏幕滚动到 div 的顶部!--抱怨,因为这对我来说是最重要的谷歌结果) (54认同)
  • 你不需要锚。只需转到#GridDiv。 (6认同)