使用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.