Home >Web Front-end >JS Tutorial >JQuery simply implements smooth scrolling of anchor links_jquery
Generally, when using an anchor point to jump to a specified position on the page, it will jump to the specified position immediately. But sometimes we want to smoothly transition to the specified position, then we can use JQuery to simply achieve this effect. :
For example, here we will jump to the specified location with the id of content by clicking the 3499910bf9dac5ae3c52d5ede7383485 tag.
<a id="turnToContent" href="#content"></a>
Then, we set the content block with the id as content at the location we want. Here, a div is used to simulate an article that does not look like an article. It is best to place this div at the back so that the effect is more obvious. If you just want to test this effect, you can use a simple and crude method and put many e388a4556c0f65e1904146cc1a846bee tags in front of it.
<div id="content"> <h2> <a href="###">HTML5</a> </h2> <p> html5html5html5 </p> <p class="addMes">标签: <span>HTML5</span><small>2015年4月19日</small></p> </div>
Finally, JQuery is used to achieve the smooth transition effect:
$('#turnToContent').click(function () { $('html, body').animate({ scrollTop: $($.attr(this, 'href')).offset().top }, 500); return false; });
Done!
Let’s continue to improve it,
$(function(){ $('a[href*=#],area[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; } } }); })
The advantage of the improved code is that clicking the anchor link will smoothly scroll to the anchor point, and the browser URL suffix does not have the word anchor. It can be implemented without modifying the above code during use.
The above is the entire content of this article, I hope you all like it.