on page load change to anchor

2019-07-24 00:19发布

问题:

I'm using Jquery.Localscroll to move the window smoothly between anchors. How would you change the URL when the page loads to include an anchor link so it scrolls smoothly to a section when the page loads.

Or is there a better way to scroll to a section when the document loads.

Thanks.

回答1:

Obviously if you specify the anchor to scroll to in the tradional way:

<a href="yourURL#someanchor">Link</a>

Then the browser will scroll automatically.

If your intention is for the browser to load the page and then have your code kick in to do a smooth (animated) scroll to a particular anchor then something like this would work:

// on calling page
<a href="yourURL?scrollto=someanchor">Link</a>

// on "yourURL" page:
$(document).ready(function() {
   // check for "scrollto" parameter and if it exists
   // use Localscroll to move to specified anchor
   var match = /[?&]scrollto(?:=([^&]*))?/.exec(window.location.search);
   if( match != null ){
      var anchor = match[1];
      // your code to scroll to anchor here
   }
});