Home  >  Article  >  Web Front-end  >  JQuery简单实现锚点链接的平滑滚动_jquery

JQuery简单实现锚点链接的平滑滚动_jquery

WBOY
WBOYOriginal
2016-05-16 16:01:371685browse

一般使用锚点来跳转到页面指定位置的时候,会生硬地立即跳转到指定位置,但是有些时候我们想要平滑地过渡到指定的位置,那么可以使用JQuery简单的实现这个效果:

比如,这里我们将通过点击标签跳转到 id为content的指定位置那里。

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

然后呢,就在我们想要的位置设置id为content的内容块,这里用一个div模拟一篇不像文章的文章。最好将此div放在靠后的位置,这样效果就很明显一点,如果只是测试一下这个效果,可以用简单粗暴的方法,在其前面放很多个

标签即可。

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

最后就是用JQuery来实现平滑过渡的效果了:

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

搞定了!

下面我们来继续改进一下,

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

改进后的代码的好处是点击锚点链接平滑滚动到锚点,并且浏览器URL后缀不带有锚点字样,使用的过程中基本不用修改以上代码即可实现。

以上所述就是本文的全部内容了,希望大家能够喜欢。

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