在页面加载时动画滚动到 ID [英] Animate scroll to ID on page load

查看:28
本文介绍了在页面加载时动画滚动到 ID的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在页面加载时动画滚动到特定 ID.我做了很多研究,发现了这个:

Im tring to animate the scroll to a particular ID on page load. I have done lots of research and came across this:

$("html, body").animate({ scrollTop: $('#title1').height() }, 1000);

但这好像是从ID开始,动画到页面顶部?

but this seems to start from the ID and animate to the top of the page?

HTML(位于页面的一半)很简单:

The HTML (which is half way down the page) is simply:

<h2 id="title1">Title here</h2>

推荐答案

您只是在滚动元素的高度.offset() 返回元素相对于文档的坐标,top 参数会给你元素沿 y 轴的距离(以像素为单位):

You are only scrolling the height of your element. offset() returns the coordinates of an element relative to the document, and top param will give you the element's distance in pixels along the y-axis:

$("html, body").animate({ scrollTop: $('#title1').offset().top }, 1000);

您还可以为其添加延迟:

And you can also add a delay to it:

$("html, body").delay(2000).animate({scrollTop: $('#title1').offset().top }, 2000);

这篇关于在页面加载时动画滚动到 ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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