问题描述:

Is it possible to have a link to another page on your site, but have the browser scrolled to an anchor div? For example most of my site's content is on the homepage, divided in sections such as about, contact, etc.

I want to be able to link from another sub page, to one of these divs.

The following code does just this, but only works when the link is on the same page as the destination:

<a href="#about" id="about-link">About</a>

The JS:

$("#about-link").click(function() {

$('html, body').animate({

scrollTop: $(".wrapper_about").offset().top

}, 0);

});

网友答案:

Your link has to include the other page's filename (and filepath, if it's not in the same directory):

<a href="other_page.html#about" id="about-link">About</a>
网友答案:

I've gotten it to work by applying this method:

<a href="#about" id="about-link">About</a>

The JS:

$("#about-link").click(function() {
  $('html, body').animate({
    scrollTop: $(window.location.hash).offset().top // Target hash not div
  }, 0);
});

It's important to note that your href target must match the ID of the element you want to anchor to.

相关阅读:
Top