54

我有一个 HTML 文档,目前有一些使用锚点指向页面顶部的链接

<body id="topofpage">
   ...
   <a href="#topofpage">Go to top</a>

但是,我不喜欢创建一个无用的 id 以及单击链接后“#topofpage”如何显示在 URL 中。在不使用 Javascript 的情况下,我还能做些什么来链接到页面顶部?我尝试完全删除锚点,<a href="">但这会导致页面刷新。

4

5 回答 5

91

根据 HTML5规范,空片段#和特殊片段#top将链接到页面顶部。

<a href="#">Go to top</a>

<a href="#top">Go to top</a>

如果您使用这些特殊的片段名称,则无需创建匹配的锚点。

于 2012-08-01T02:22:40.030 回答
12

您可以尝试使用 javascript

<a onclick="scroll(0,0)">

或者你可以使用 jQuery

$("#Top").click(function(){
 scroll(0,0);
});
于 2012-08-01T00:23:27.200 回答
7

I know that you said without using JavaScript, but I think that is really the only way to avoid using a real anchor. The following jQuery will replace anchors with the #top href and perform a nice animated scroll to the top without the URL changing (see the original author's page for more info).

$(document).ready(function() {
    $('a[href=#top]').click(function(){
        $('html, body').animate({scrollTop:0}, 'slow');
        return false;
    });
})

jsfiddle for completeness

However, I would stick with semantic HTML and use anchors for their purpose so that the proper meaning can be interpreted by the maximum number of browsers. Don't forget about people with disabilities that require screen readers or other special browsers. Anchors are guaranteed to work.

In addition to that, Google announced in 2009 some new indexing features that directly take advantage of in-page anchors to provide additional context that the Web searcher might be looking for. In many cases, there might be a section of a page that a user is very interested in. Google can provide a direct link to that anchor of the page for optimum relevance.

Bottom line from my point of view - don't dis the anchors. Use them.

于 2012-08-01T02:32:40.113 回答
2

另一种使用锚标记获取页面顶部的有用方法是

<a href='#top'> Go back to the top of the page.</a>

像这样使用它会使您的页面自动滚动到当前页面的顶部。希望这对某人有用。

于 2017-06-22T02:41:14.000 回答
-5

<a href="?">top</a>会带你到那里。

于 2012-08-01T15:22:41.710 回答