hash in anchor tags

How do I load a page and get it to open at a certain location of the loaded page?

For example, lets say I have page1.html , which has 3 links

<a href="page2.html#1">1</a>
<a href="page2.html#2">2</a>
<a href="page2.html#3">3</a>

on page2.html , I have those links on the page also, ie

<a href="page3.html#1">1</a>
<a href="page3.html#2">2</a>
<a href="page3.html#3">3</a>

but when I click on the #2 or #3 link from page1.html , they always open at the top of the page, even though #2 and #3 are off the screen on page2.html which need to be scrolled down to to be seen.

Not sure what I am doing wrong.


You need to put named anchors on page2.html , like so:

<a name="1"></a>
…
<a name="2"></a>
…
<a name="3"></a>

– This was before HTML5. Nowadays, you use id instead of name .


You need to add an ID to the element that it should 'jump' to.

For example, if you have

<div id="part1">
  <p>Blah blah blah</p>
</div>

<div id="part2">
  <p>Blah blah blah</p>
</div>

<div id="part3">
  <p>Blah blah blah</p>
</div>

And they are all in page.html

Then you can link to page.html#part1 , page.html#part2 etc etc and it will jump to the correct part of the page

Update:

You can also use the name attribute however I prefer to use id. This is because anything can have a id but not necessarily a name. For example I don't think name is a valid attribute for an 'a' tag in HTML 5. Also if you have one element with id="part1" and another different element with name="part1", the one with the id will take precendence. To avoid confusion, I just stick with the one method throughout. There's a bit more of a discussion on this here


Use of the name attribute or id attribute in an anchor tag on the target page would accomplish the desired result.

<a name="someLocation" id="someLocation">SomeText</a>

As an XHTML 1.1 convention, the name attribute of an anchor tag has been replaced by the id attribute. In the context of XHTML 1.0, the name attribute is considered deprecated.

See this answer for a related discussion on changes to the anchor tag.

To summarize: for compatibility reasons, many suggest the use of both an id attribute and a name attribute, within the same element. In this case, an anchor tag.

The W3C Standard recommends (with respect to all applicable elements):

The id and name attributes share the same name space. This means that they cannot both define an anchor with the same name in the same document. It is permissible to use both attributes to specify an element's unique identifier for the following elements: A, APPLET, FORM, FRAME, IFRAME, IMG, and MAP. When both attributes are used on a single element, their values must be identical.

Apologies for any duplication, I lack the reputation to comment on the best answer.

链接地址: http://www.djcxy.com/p/88978.html

上一篇: 锚点击并保持页面位置?

下一篇: 散列在锚标记中