JQuery provides smooth scrolling between anchor links on the same page

  • 2020-03-30 04:13:26
  • OfStack

Web development front-end has been using JQuery, really touched to realize that JQuery is much more powerful than I imagined, may also be much more powerful than I realized, especially compatibility that is good, so some fun, cool, can replace JS, all to use.

Introduce today's topic from JQuery and use JQuery to achieve smooth scrolling between anchor links. Introduces a use JS before implementation of anchor point jump page buffer effects, the effect is quite good, can be on the same page of the anchor links between smooth scrolling, but the JS code is relatively long, now good, as long as the JQuery frame have been loaded, we can achieve the same effect with relatively short code.

Usage:

1. Load JQuery library;

2. Key codes:


$(document).ready(function() { 
$('a[href*=#]').click(function() { 
if (location.pathname.replace(/^//, '') == this.pathname.replace(/^//, '') && location.hostname == this.hostname) { 
var $target = $(this.hash); 
$target = $target.length && $target || $('[name=' + this.hash.slice(1) + ']'); 
if ($target.length) { 
var targetOffset = $target.offset().top; 
$('html,body').animate({ 
scrollTop: targetOffset 
}, 
1000); 
return false; 
} 
} 
}); 
});

Again, to emphasize the loading order, refer to the JQuery class library. By the way, the scrolling effect has been tested to be compatible with all browsers, except for Opera, which is a bit weird and could be improved.


Related articles: