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

查看:109
本文介绍了在页面加载时将动画滚动到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天全站免登陆