Home  >  Article  >  Web Front-end  >  JQuery implements smooth scrolling between anchor links on the same page_jquery

JQuery implements smooth scrolling between anchor links on the same page_jquery

WBOY
WBOYOriginal
2016-05-16 16:32:461242browse

I have always used JQuery for web development front-end. Only after I got in touch with it did I realize that JQuery is much more powerful than I thought, and it may be much more powerful than I realized, especially the one with better compatibility, so I decided to use JQuery. Some fun and cool things, which can replace JS, are all used.

Introducing today’s topic from JQuery, using JQuery to achieve smooth scrolling between anchor links. I have previously introduced a page anchor jump buffer effect implemented using JS. The effect is quite good and can achieve smooth scrolling between anchor links on the same page. However, the JS code is relatively lengthy. Now it is better. As long as it has been With JQuery loaded, we can achieve the same effect with shorter code.

How to use it:

1. Load the JQuery library;

2. Key code:

$(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; 
} 
} 
}); 
});

I still want to emphasize the loading order, first refer to the JQuery class library. By the way, after testing, the scrolling effect is compatible and applicable in all browsers, but it behaves a bit weird under Opera and needs to be improved.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn