使用jQuery在div中滚动 [英] scroll within div using jquery

查看:74
本文介绍了使用jQuery在div中滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个<div>overflow:auto.此<div>包含带有搜索栏的<form>. 我以相同的形式显示获取的记录,现在我所要做的就是将<div>(搜索结果开始显示在其中)滚动到其容器<div>的顶部(而不是页面的顶部)

I have one <div> with overflow:auto. This <div> contains a <form> with a Search bar. I am displaying the records fetched, in the same form, now all I need is to scroll the <div> (where my search results start displaying) to the top of its container <div> (and not to the top of the page).

检查创建的jsfiddle. http://jsfiddle.net/tusharjs/wGUE2/15/

check the jsfiddle created. http://jsfiddle.net/tusharjs/wGUE2/15/

在这里,我尝试了在stackoverflow上找到的解决方案,但是它将所需的<div id="scrollto">滚动到页面顶部而不是<div id="maincontent">顶部.

Here, I have tried a solution I found on stackoverflow, but it scrolls the desired <div id="scrollto"> to top of page and not to the top of the <div id="maincontent">.

谢谢

推荐答案

您应该使用.offset()方法获取元素的实际顶部,然后从要滚动的数量中减去该顶部.

You should use the .offset() method to get the element's actual top and subtract that from the amount to scroll.

$(document).ready( function(){
  var elem = $('#scrollto');
  if(elem)
  {
    var main = $("#maincontent"),
        t = main.offset().top;
        main.scrollTop(elem.offset().top - t);
  }
});

这是我的小提琴叉子

对滚动进行动画处理可能会更加令人印象深刻:

It might be more impressive to animate the scroll:

main.animate({scrollTop: elem.offset().top - t}, 500);

上面的第二个参数是持续时间(以毫秒为单位).更新的示例是此处.

The second parameter above is the duration in milliseconds. The updated example is here.

这篇关于使用jQuery在div中滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆