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

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

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

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

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


Copy after login

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

标签即可。

HTML5

html5html5html5

标签: HTML52015年4月19日

Copy after login

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

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

搞定了!

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

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

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

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

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!