平滑滚动(Smooth Scroll)jquery

2014.10.12 分享 33228 人浏览 9 条留言

很简单的小玩意

演示地址:https://huilang.me/jquery/smooth-scroll.html

平滑滚动,这里的意思是,举个例子,有如下html结构

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="UTF-8" />
  5.         <title>平滑滚动(Smooth Scroll)jquery</title>
  6.         <style>
  7.             body { font-family: Arial, "Helvetica Neue", Helvetica, sans-serif; line-height: 1.5em; }
  8.             .huilang { max-width: 600px; margin: 0 auto; min-height: 2000px; }
  9.             .nav { position: fixed; top: 0; left: 0; }
  10.             .nav li { display: inline-block; }
  11.             .nav li a { display: block; }
  12.             #top, #contact, #about { min-height: 500px; border-top: 1px solid #000; }
  13.             h2 { font-size: 20px; text-align: center; margin-bottom: 20px; }
  14.         </style>
  15.     </head>
  16.     <body>
  17.         <div class="huilang">
  18.             <div class="nav">
  19.                 <ul>
  20.                     <li><a href="#top">Welcome</a></li>
  21.                     <li><a href="#contact">Contact</a></li>
  22.                     <li><a href="#about">About</a></li>
  23.                 </ul>
  24.             </div>
  25.             <div id="top">
  26.                 <h2>Welcome</h2> Welcome to my blog.
  27.             </div>
  28.             <div id="contact">
  29.                 <h2>Contact me</h2>E-mail:[email protected]<br>Url:https://huilang.me
  30.             </div>
  31.             <div id="about">
  32.                 <h2>About me</h2>I am huilang
  33.             </div>
  34.         </div>
  35.     </body>
  36. </html>

想要实现的效果是,点击Welcome,页面缓慢平滑地滚动到顶部#top,点击Contact,页面缓慢平滑地滚动到contact的位置#contact,about同理。

这里说下平滑滚动的两种方法(都必须先加载jquery)

1.Smooth Scroll Plugin

加载该js(建议下载到本地)

  1. <script src="https://raw.githubusercontent.com/kswedberg/jquery-smooth-scroll/master/jquery.smooth-scroll.js"></script>

然后进行调用(详见 https://github.com/kswedberg/jquery-smooth-scroll)

  1. $('#container a').smoothScroll({offset: - 30});

2.简单粗暴,给所有a标签的链接地址为#xxx的加上滚动效果(需要在线测试,本地无效)

  1. $(function() {
  2.   $('a[href*=#]:not([href=#])').click(function() {
  3.       if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  4.       var target = $(this.hash);
  5.       target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  6.       if (target.length) {
  7.             $('html,body').animate({
  8.           scrollTop: target.offset().top - 34
  9.         }, 1000);
  10.         return false;
  11.       }
  12.     }
  13.   });
  14. });

当然你也可以改成指定的class

扩展

如果你想显示当前滚动所在的位置,可以加载一个jq Plugin - jQuery Waypoints,实现更好的效果,这里就不多做描述,详见https://github.com/imakewebthings/jquery-waypoints。

最终版代码如下

  1. <!DOCTYPE html>
  2. <html>
  3.     <head>
  4.         <meta charset="UTF-8" />
  5.         <script type='text/javascript' src='https://huilang.me/wp-includes/js/jquery/jquery.js'></script>
  6.         <script>
  7.             /*
  8.             jQuery Waypoints - v2.0.4
  9.             Copyright (c) 2011-2014 Caleb Troughton
  10.             Dual licensed under the MIT license and GPL license.
  11.             https://github.com/imakewebthings/jquery-waypoints/blob/master/licenses.txt
  12.             */
  13.             (function(){var t=[].indexOf||function(t){for(var e=0,n=this.length;e<n;e++){if(e in this&&this[e]===t)return e}return-1},e=[].slice;(function(t,e){if(typeof define==="function"&&define.amd){return define("waypoints",["jquery"],function(n){return e(n,t)})}else{return e(t.jQuery,t)}})(this,function(n,r){var i,o,l,s,f,u,c,a,h,d,p,y,v,w,g,m;i=n(r);a=t.call(r,"ontouchstart")>=0;s={horizontal:{},vertical:{}};f=1;c={};u="waypoints-context-id";p="resize.waypoints";y="scroll.waypoints";v=1;w="waypoints-waypoint-ids";g="waypoint";m="waypoints";o=function(){function t(t){var e=this;this.$element=t;tthis.element=t[0];this.didResize=false;this.didScroll=false;this.id="context"+f++;this.oldScroll={x:t.scrollLeft(),y:t.scrollTop()};this.waypoints={horizontal:{},vertical:{}};this.element[u]=this.id;c[this.id]=this;t.bind(y,function(){var t;if(!(e.didScroll||a)){e.didScroll=true;t=function(){e.doScroll();return e.didScroll=false};return r.setTimeout(t,n[m].settings.scrollThrottle)}});t.bind(p,function(){var t;if(!e.didResize){e.didResize=true;t=function(){n[m]("refresh");return e.didResize=false};return r.setTimeout(t,n[m].settings.resizeThrottle)}})}t.prototype.doScroll=function(){var t,e=this;t={horizontal:{newScroll:this.$element.scrollLeft(),oldScroll:this.oldScroll.x,forward:"right",backward:"left"},vertical:{newScroll:this.$element.scrollTop(),oldScroll:this.oldScroll.y,forward:"down",backward:"up"}};if(a&&(!t.vertical.oldScroll||!t.vertical.newScroll)){n[m]("refresh")}n.each(t,function(t,r){var i,o,l;l=[];o=r.newScroll>r.oldScroll;i=o?r.forward:r.backward;n.each(e.waypoints[t],function(t,e){var n,i;if(r.oldScroll<(n=e.offset)&&n<=r.newScroll){return l.push(e)}else if(r.newScroll<(i=e.offset)&&i<=r.oldScroll){return l.push(e)}});l.sort(function(t,e){return t.offset-e.offset});if(!o){l.reverse()}return n.each(l,function(t,e){if(e.options.continuous||t===l.length-1){return e.trigger([i])}})});return this.oldScroll={x:t.horizontal.newScroll,y:t.vertical.newScroll}};t.prototype.refresh=function(){var t,e,r,i=this;r=n.isWindow(this.element);e=this.$element.offset();this.doScroll();t={horizontal:{contextOffset:r?0:e.left,contextScroll:r?0:this.oldScroll.x,contextDimension:this.$element.width(),oldScroll:this.oldScroll.x,forward:"right",backward:"left",offsetProp:"left"},vertical:{contextOffset:r?0:e.top,contextScroll:r?0:this.oldScroll.y,contextDimension:r?n[m]("viewportHeight"):this.$element.height(),oldScroll:this.oldScroll.y,forward:"down",backward:"up",offsetProp:"top"}};return n.each(t,function(t,e){return n.each(i.waypoints[t],function(t,r){var i,o,l,s,f;i=r.options.offset;l=r.offset;o=n.isWindow(r.element)?0:r.$element.offset()[e.offsetProp];if(n.isFunction(i)){ii=i.apply(r.element)}else if(typeof i==="string"){i=parseFloat(i);if(r.options.offset.indexOf("%")>-1){i=Math.ceil(e.contextDimension*i/100)}}r.offset=o-e.contextOffset+e.contextScroll-i;if(r.options.onlyOnScroll&&l!=null||!r.enabled){return}if(l!==null&&l<(s=e.oldScroll)&&s<=r.offset){return r.trigger([e.backward])}else if(l!==null&&l>(f=e.oldScroll)&&f>=r.offset){return r.trigger([e.forward])}else if(l===null&&e.oldScroll>=r.offset){return r.trigger([e.forward])}})})};t.prototype.checkEmpty=function(){if(n.isEmptyObject(this.waypoints.horizontal)&&n.isEmptyObject(this.waypoints.vertical)){this.$element.unbind([p,y].join(" "));return delete c[this.id]}};return t}();l=function(){function t(t,e,r){var i,o;r=n.extend({},n.fn[g].defaults,r);if(r.offset==="bottom-in-view"){r.offset=function(){var t;t=n[m]("viewportHeight");if(!n.isWindow(e.element)){t=e.$element.height()}return t-n(this).outerHeight()}}this.$element=t;tthis.element=t[0];this.axis=r.horizontal?"horizontal":"vertical";this.callback=r.handler;this.context=e;this.enabled=r.enabled;this.id="waypoints"+v++;this.offset=null;this.options=r;e.waypoints[this.axis][this.id]=this;s[this.axis][this.id]=this;i=(o=this.element[w])!=null?o:[];i.push(this.id);this.element[w]=i}t.prototype.trigger=function(t){if(!this.enabled){return}if(this.callback!=null){this.callback.apply(this.element,t)}if(this.options.triggerOnce){return this.destroy()}};t.prototype.disable=function(){return this.enabled=false};t.prototype.enable=function(){this.context.refresh();return this.enabled=true};t.prototype.destroy=function(){delete s[this.axis][this.id];delete this.context.waypoints[this.axis][this.id];return this.context.checkEmpty()};t.getWaypointsByElement=function(t){var e,r;r=t[w];if(!r){return[]}e=n.extend({},s.horizontal,s.vertical);return n.map(r,function(t){return e[t]})};return t}();d={init:function(t,e){var r;if(e==null){e={}}if((r=e.handler)==null){e.handler=t}this.each(function(){var t,r,i,s;t=n(this);i=(s=e.context)!=null?s:n.fn[g].defaults.context;if(!n.isWindow(i)){i=t.closest(i)}i=n(i);r=c[i[0][u]];if(!r){r=new o(i)}return new l(t,r,e)});n[m]("refresh");return this},disable:function(){return d._invoke.call(this,"disable")},enable:function(){return d._invoke.call(this,"enable")},destroy:function(){return d._invoke.call(this,"destroy")},prev:function(t,e){return d._traverse.call(this,t,e,function(t,e,n){if(e>0){return t.push(n[e-1])}})},next:function(t,e){return d._traverse.call(this,t,e,function(t,e,n){if(e<n.length-1){return t.push(n[e+1])}})},_traverse:function(t,e,i){var o,l;if(t==null){t="vertical"}if(e==null){e=r}l=h.aggregate(e);o=[];this.each(function(){var e;e=n.inArray(this,l[t]);return i(o,e,l[t])});return this.pushStack(o)},_invoke:function(t){this.each(function(){var e;e=l.getWaypointsByElement(this);return n.each(e,function(e,n){n[t]();return true})});return this}};n.fn[g]=function(){var t,r;r=arguments[0],t=2<=arguments.length?e.call(arguments,1):[];if(d[r]){return d[r].apply(this,t)}else if(n.isFunction(r)){return d.init.apply(this,arguments)}else if(n.isPlainObject(r)){return d.init.apply(this,[null,r])}else if(!r){return n.error("jQuery Waypoints needs a callback function or handler option.")}else{return n.error("The "+r+" method does not exist in jQuery Waypoints.")}};n.fn[g].defaults={context:r,continuous:true,enabled:true,horizontal:false,offset:0,triggerOnce:false};h={refresh:function(){return n.each(c,function(t,e){return e.refresh()})},viewportHeight:function(){var t;return(t=r.innerHeight)!=null?t:i.height()},aggregate:function(t){var e,r,i;e=s;if(t){e=(i=c[n(t)[0][u]])!=null?i.waypoints:void 0}if(!e){return[]}r={horizontal:[],vertical:[]};n.each(r,function(t,i){n.each(e[t],function(t,e){return i.push(e)});i.sort(function(t,e){return t.offset-e.offset});r[t]=n.map(i,function(t){return t.element});return r[t]=n.unique(r[t])});return r},above:function(t){if(t==null){t=r}return h._filter(t,"vertical",function(t,e){return e.offset<=t.oldScroll.y})},below:function(t){if(t==null){t=r}return h._filter(t,"vertical",function(t,e){return e.offset>t.oldScroll.y})},left:function(t){if(t==null){t=r}return h._filter(t,"horizontal",function(t,e){return e.offset<=t.oldScroll.x})},right:function(t){if(t==null){t=r}return h._filter(t,"horizontal",function(t,e){return e.offset>t.oldScroll.x})},enable:function(){return h._invoke("enable")},disable:function(){return h._invoke("disable")},destroy:function(){return h._invoke("destroy")},extendFn:function(t,e){return d[t]=e},_invoke:function(t){var e;e=n.extend({},s.vertical,s.horizontal);return n.each(e,function(e,n){n[t]();return true})},_filter:function(t,e,r){var i,o;i=c[n(t)[0][u]];if(!i){return[]}o=[];n.each(i.waypoints[e],function(t,e){if(r(i,e)){return o.push(e)}});o.sort(function(t,e){return t.offset-e.offset});return n.map(o,function(t){return t.element})}};n[m]=function(){var t,n;n=arguments[0],t=2<=arguments.length?e.call(arguments,1):[];if(h[n]){return h[n].apply(null,t)}else{return h.aggregate.call(null,n)}};n[m].settings={resizeThrottle:100,scrollThrottle:30};return i.load(function(){return n[m]("refresh")})})}).call(this);
  14.             //You can start here
  15.             (function ($, window, undefined) {
  16.                 $(document).ready(function(){
  17.                     $('a[href*=#]:not([href=#])').click(function() {
  18.                         if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
  19.                             var target = $(this.hash);
  20.                             targettarget = target.length ? target : $('[name=' + this.hash.slice(1) +']');
  21.                             if (target.length) {
  22.                                 $('html,body').animate({
  23.                                     scrollTop: target.offset().top - 15
  24.                                 }, 1000);
  25.                                 return false;
  26.                             }
  27.                         }
  28.                     });
  29.                     $('#welcome').waypoint(function(direction) {
  30.                         $('.nav li').removeClass('active');
  31.                         if(direction == 'down')
  32.                         $('.welcome').addClass('active');
  33.                     }, { offset: 15 });
  34.                     $('#contact').waypoint(function(direction) {
  35.                         $('.nav li').removeClass('active');
  36.                         if(direction == 'down')
  37.                             $('.contact').addClass('active');
  38.                         else
  39.                             $('.welcome').addClass('active');
  40.                     }, { offset: 15 });
  41.                     $('#about').waypoint(function(direction) {
  42.                         $('.nav li').removeClass('active');
  43.                         if(direction == 'down')
  44.                         $('.about').addClass('active');
  45.                         else
  46.                             $('.contact').addClass('active');
  47.                     }, { offset: 15 });
  48.                 });
  49.             })(jQuery, window);
  50.         </script>
  51.         <title>平滑滚动(Smooth Scroll)jquery</title>
  52.         <style>
  53.             body { font-family: Arial, "Helvetica Neue", Helvetica, sans-serif; line-height: 1.5em; }
  54.             .huilang { max-width: 300px; margin: 0 auto; min-height: 2000px; }
  55.             .nav { position: fixed; top: 0; left: 0; }
  56.             .nav li {margin-bottom: 10px; }
  57.             .nav li a { display: block; color: #000;}
  58.             .nav li.active a{font-weight: bold;color: red}
  59.             #welcome, #contact, #about { min-height: 500px; border-top: 1px solid #000; }
  60.             h2 { font-size: 20px; text-align: center; margin-bottom: 20px; }
  61.         </style>
  62.     </head>
  63.     <body>
  64.         <div class="huilang">
  65.             <div class="nav">
  66.                 <ul>
  67.                     <li class="welcome"><a href="#welcome">Welcome</a></li>
  68.                     <li class="contact"><a href="#contact">Contact</a></li>
  69.                     <li class="about"><a href="#about">About</a></li>
  70.                 </ul>
  71.             </div>
  72.             <div id="welcome">
  73.                 <h2>Welcome</h2> Welcome to my blog.<br> <a target="_blank" href="https://huilang.me/jquery-smooth-scroll/">Click here to see more</a>
  74.             </div>
  75.             <div id="contact">
  76.                 <h2>Contact me</h2>E-mail:[email protected]<br>Url:https://huilang.me
  77.             </div>
  78.             <div id="about">
  79.                 <h2>About me</h2>I am huilang
  80.             </div>
  81.         </div>
  82.     </body>
  83. </html>

我不会告诉你这是我的笔记

文章地址:https://huilang.me/jquery-smooth-scroll/

“平滑滚动(Smooth Scroll)jquery” 有 9 条评论

  1. Aaron说道:

    有点QQ空间时光轴瘔感觉。

  2. zwwooooo说道:

    比直接简单用 jq 的效果赞(平滑了),不过那么一大坨 jq 感觉不值,当然现在都可以无视了

  3. 秘方网说道:

    这么多代码会不会运行得很慢呢。

  4. 歌词大全说道:

    谢谢分享,说不定哪天会用到的呢。

  5. 琉璃瓦说道:

    我怎么不太会用这些代码啊

  6. 钟水洲说道:

    本站已开通投稿奖励,欢迎投稿!

记忆碎片进行回复 取消回复

电子邮件地址不会被公开。 必填项已用*标注

icon_wink.gif icon_neutral.gif icon_mad.gif icon_twisted.gif icon_smile.gif icon_eek.gif icon_sad.gif icon_rolleyes.gif icon_razz.gif icon_redface.gif icon_surprised.gif icon_mrgreen.gif icon_lol.gif icon_idea.gif icon_biggrin.gif icon_evil.gif icon_cry.gif icon_cool.gif icon_arrow.gif icon_confused.gif icon_question.gif icon_exclaim.gif