JQuery simply implements smooth scrolling of anchor links

  • 2020-06-03 05:52:26
  • OfStack

Generally, when using anchor points to jump to the specified position on the page, it will immediately jump to the specified position stiffly, but sometimes we want to smooth the transition to the specified position, so we can use JQuery to achieve this effect simply:

For example, here we're going to click < a > The tag jumps to the location specified by id for content.


<a id="turnToContent" href="#content"></a>

Then, set id to content's content block where we want it to be, using 1 div to simulate an article that doesn't look like an article. It is best to place this div at the back so that the effect is obvious 1 point. If you are just testing the effect 1, you can use a simple and crude method and put many in front of it < p > The label is enough.


<div id="content">
<h2>
<a href="###">HTML5</a>
</h2>
<p>
html5html5html5
</p>
<p class="addMes"> Tags: &nbsp;<span>HTML5</span><small>2015 years 4 month 19 day </small></p>
</div>

Finally, JQuery is used for smooth transitions:


$('#turnToContent').click(function () {
$('html, body').animate({
scrollTop: $($.attr(this, 'href')).offset().top
}, 500);
return false;
});

Done!

So let's go ahead and make one more improvement,


$(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 on the anchor link smoothly scrolls to the anchor, and the browser's URL suffix does not carry the word "anchor", so it can be used with little modification.

This is the end of this article, I hope you enjoy it.


Related articles: