滚动到javascript或jquery中具有特定ID的html元素 [英] Scroll to an html element with a particular id in javascript or jquery
问题描述
我有分配了ID的html元素.现在,我想滚动到那些元素.我看到jQuery有一个采用整数值的scrollTop.如何简单地使一个具有id的特定html元素滚动到顶部?理想情况下,具有优美而流畅的动画.
I have html elements with id's assigned. Now I want to scroll to those elements. I see jQuery has a scrollTop which takes an integer value.. How do I easily just make a particular html element with an id scroll to the top? Ideally, with nice and smooth animation.
快速搜索显示了许多滚动插件...如果上述功能需要插件,那么最受欢迎的插件是什么?我也在使用jquery-ui.
A quick search showed many scrolling plugins... if a plugin is needed for the above functionality, what's the most popular one? I'm also using jquery-ui.
推荐答案
在页面加载时,您可以使用类似的方法滚动到#someElement
:
You could use something like this to scroll to #someElement
when the page loads:
$(document).ready(function() {
$("html, body").animate({scrollTop: $("#someElement").offset().top}, 1000);
});
它只是为body
元素的scrollTop
属性设置动画,并使用某些特定元素的顶部偏移量作为滚动到的位置.动画持续1000毫秒.
It simply animates the scrollTop
property of the body
element, and uses the top offset of some specific element as the position to scroll to. The animation lasts for 1000ms.
注意:它同时选择html
和body
,因此可以在浏览器中使用.我不确定具体细节,但是一些快速测试表明Chrome使用body
,但是Firefox和IE使用html
.
Note: it selects both html
and body
so it works across browsers. I'm not sure on the specifics, but some quick tests show that Chrome uses body
, but Firefox and IE use html
.
这是一个工作示例.
这篇关于滚动到javascript或jquery中具有特定ID的html元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!