Safari anchors on links not working

2019-01-12 06:58发布

问题:

My html anchor is as follows.

<a name="template-8"/>
<h4 class="template" id="template-8">A title</h4>

As far as I know the browser should skip to the element with a matching name or id attribute.

When I type in the url http://my.site.com/templates#template-8 safari jumps down the page as expected.

However when linking as below the anchor does nothing. Chrome, Opera, IE7 and Firefox all work.

<a href="http://my.site.com/templates#template-8">A link</a>

Safari is version 5.0, could this be a safari bug?

回答1:

The problem was I had a redirect header in the page I was linking to.

Opera, IE, Chrome, Firefox will carry over the anchor to the new page. However safari loses the anchor on the redirect.

If you are having trouble with safari anchors disable any redirects.



回答2:

For me, I simply had to change

http://domain.com/page#myanchor 

to

http://domain.com/page/#myanchor


回答3:

I just ran into the same issue and found your post while searching - obviously you've fixed this since it was back in 2010 and but figured I would post what I found in case someone else finds this. :)

I'm using htaccess to redirect my url from mydomaincom/index.php to mydomaincom/ and found that my nav didn't work in Safari since my href addresses where index.php#value and Safari v5 wouldn't carry over the anchor links.

Rather than turn off my redirect I just changed the urls to point to mydomaincom/#value. Not only did this work great for all browsers but it also made my page quicker (not yet sure how but will search this now :))



回答4:

There are two side issues I see, which aren't the cause (since you found the problem already) but probably don't help:

  • Self-closing <a> tag. You can't self-close tags that are supposed to have end tags, it should be: <a name="template-8"></a>.
  • The name and id attributes share the same "namespace", so you cannot have the same value for a name and id attribute. All browsers from the past 10 years support anchors on IDs, so scrap that useless link tag.


回答5:

To fix an anchor tag in Safari. I proceed this way :

 <a href="#" class="btn">A tag</a>

And on my css file :

.btn{
  display:block;
  width:100%;
  height:100%;
}

The important thing is for some reason, sometimes Safari needs to see your link as a block, and it can be useful if you create a list, with some links inside. Example :

<ul>
    <li><a href="#" class="btn">A tag</a></li>
    <li><a href="#" class="btn">A tag</a></li>
</ul>

Works for Safari 6+