Home > Web Front-end > JS Tutorial > body text

JQuery simply implements smooth scrolling of anchor links_jquery

WBOY
Release: 2016-05-16 16:01:37
Original
1717 people have browsed it

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 tag.

<a id="turnToContent" href="#content"></a>
Copy after login

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

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>
Copy after login

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;
});
Copy after login

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;
      }
    }
  });
})
Copy after login

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.

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!