是否可以使用 jQuery 滚动到页面上的特定位置?
我要滚动的位置是否必须有:
<a name="#123">here</a>
或者它可以移动到特定的 DOM id?
最佳答案
jQuery 滚动插件
因为这是一个用 jquery 标记的问题,我不得不说,这个库有一个非常好的平滑滚动插件,你可以在这里找到它: http://plugins.jquery.com/scrollTo/
文档摘录:
$('div.pane').scrollTo(...);//all divs w/class pane
或
$.scrollTo(...);//the plugin will take care of this
用于滚动的自定义 jQuery 函数
您可以通过定义自定义滚动 jquery 函数来使用非常轻量级的方法
$.fn.scrollView = function () {
return this.each(function () {
$('html, body').animate({
scrollTop: $(this).offset().top
}, 1000);
});
}
并像这样使用它:
$('#your-div').scrollView();
滚动到页面坐标
使用 scrollTop
或 scrollLeft
属性为 html
和 body
元素制作动画
$('html, body').animate({
scrollTop: 0,
scrollLeft: 300
}, 1000);
纯 javascript
使用 window.scroll
滚动
window.scroll(horizontalOffset, verticalOffset);
总结一下,利用window.location.hash跳转到ID为元素
window.location.hash = '#your-page-element';
直接在 HTML 中(辅助功能增强)
<a href="#your-page-element">Jump to ID</a>
<div id="your-page-element">
will jump here
</div>
关于jquery - 如何使用 jquery 滚动到页面上的特定位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1586341/