如何将 HTML 页面滚动到给定的锚点 [英] How to scroll an HTML page to a given anchor

查看:47
本文介绍了如何将 HTML 页面滚动到给定的锚点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想让浏览器将页面滚动到给定的锚点,只需使用 JavaScript.

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

我在我的 HTML 代码中指定了 nameid 属性:

I have specified a name or id attribute in my HTML code:

 <a name="anchorName">..</a>

 <h1 id="anchorName2">..</h1>

我希望获得与导航到 http://server.com/path#anchorName 相同的效果.应滚动页面,使锚点靠近页面可见部分的顶部.

I’d like to get the same effect as you’d get by navigating to http://server.com/path#anchorName. The page should be scrolled so that the anchor is near the top of the visible part of the page.

推荐答案

function scrollTo(hash) {
    location.hash = "#" + hash;
}

根本不需要 jQuery!

No jQuery required at all!

这篇关于如何将 HTML 页面滚动到给定的锚点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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