我正在尝试在页面加载时将滚动动画到特定ID。 我做了很多研究,发现了这个:
$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);
但是这似乎从ID开始动画并向页面顶部移动?
HTML(位于页面中间)仅为:
<h2 id="title1">Title here</h2>
我正在尝试在页面加载时将滚动动画到特定ID。 我做了很多研究,发现了这个:
$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);
但是这似乎从ID开始动画并向页面顶部移动?
HTML(位于页面中间)仅为:
<h2 id="title1">Title here</h2>
你只是在滚动元素的高度。 offset() 返回元素相对于文档的坐标,top
参数将给出元素沿 y 轴的像素距离:
$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);
而且你还可以给它加上延迟:
$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);
body
或元素的当前滚动位置。有了这个想法,您将把body
的当前滚动位置添加到我们想要查看的元素的offset().top
位置中,得到的总和就是我们要滚动到的值。$('html, body').animate({ scrollTop: ($('html, body').scrollTop() + $('#title1').offset().top) }, 1000);
- mattdevio.offset().top
会给你一个负数。而且这只适用于 body
和 html
,因为 offset().top
会给出文档顶部的偏移量,而不是预期的滚动父级。 - mattdevio使用 scrollIntoView() 函数的纯 JavaScript 解决方案:
el = document.getElementById('title1')
el.scrollIntoView({block: 'start', behavior: 'smooth'});
<h2 id="title1">Some title</h2>
P.S. 'smooth'参数现在可以在Chrome 61中正常工作,如评论中julien_c所述。
废弃通知:jQuery 1.9版本中删除了jQuery.browser
属性。有关更多详细信息,请访问文档:https://api.jquery.com/jQuery.browser/
$(jQuery.browser.webkit ? "body": "html").animate({ scrollTop: $('#title1').offset().top }, 1000);
$("#title1").animatedScroll({easing: "easeOutExpo"});
href
。$('a.page-scroll').bind('click', function(event) {
var $anchor = $(this);
$('html, body').stop().animate({
scrollTop: ($($anchor.attr('href')).offset().top - 50)
}, 1250, 'easeInOutExpo');
event.preventDefault();
});
对于简单的滚动,使用以下样式
height: 200px; overflow: scroll;
并在您想要显示滚动条的 div 或 section 中使用此样式类