返回顶部的快捷按钮在web页面中普遍存在,不过有些实现得并不理想,滚动条瞬间滚到页面顶部,过程不平滑而影响用户体验。在此列举实现返回顶部的若干方法,并分析优劣。
1. 使用锚点
页面顶部元素设置一个id值,返回顶部用a标签,设置a标签的href值为刚才的顶部元素id值。代码如下:
1 <div id="container">
2 <p>足够使container出现滚动条的内容</p>
3 </div>
4 <a href="#container" id="goToTop">返回顶部</a>
利用浏览器a标签定位锚点功能,可以容易实现返回顶部,但滚动条滚动过程中并不平滑。
2. 使用DOM的scrollIntoView方法
绑定返回顶部按钮的点击事件,在回调函数中调用页面顶部元素的scrollIntoView方法。代码如下:
1 $('#goToTop').on('click', function(e){
2 //target为容器顶部元素id
3 document.getElementById('target').scrollIntoView();
4 });
scrollIntoView接受一个参数,为true时滚动条将滚动到元素的bottom位置,为false或不传时滚动条将滚动到元素的top位置。
3.使用scrollTo方法
这里使用元素的scrollTo方法,并在调用该方法时使用动画,使得滚动条滚动过程平滑。我将次实现封装了组件,代码如下:
1 //SmoothScroll
2 (function($, window, undefined){
3 function SmoothScroll(config){
4 return this._init(config);
5 }
6 SmoothScroll.prototype = {
7 constructor: SmoothScroll,
8 _init: function(config){
9 var me = this;
10 me._config = $.extend({
11 //container 滚动条的容器
12 //go2Top 返回顶部jQuery对象
13 //destination 需滚动位置的jQuery对象
14 duration: 500,//动画因子
15 scrollTop: 10
16 }, config);
17 me._cacheParam()._bindEventListener();
18 return me;
19 },
20 _cacheParam: function(){
21 var i,
22 me = this,
23 config = me._config;
24 for(i in config){
25 if(hasOwnProperty.call(config, i)){
26 me['_' + i] = config[i];
27 config[i] = null;
28 delete config[i];
29 }
30 }
31 return me;
32 },
33 _bindEventListener: function(){
34 var me = this,
35 $go2Top = me._go2Top,
36 $container = me._container;
37 me._showOrHideGo2Top();
38 $container.on('scroll.smoothccroll', function(e){
39 me._showOrHideGo2Top();
40 });
41 $go2Top.on('click.smoothccroll', function(e){
42 me._smoothScroll();
43 return false;
44 });
45 return me;
46 },
47 _smoothScroll: function(duration){
48 var step,
49 distance,
50 me = this,
51 $container = me._container,
52 destination = me._destination.offset().top;
53 duration = duration == null ? me._duration : duration;
54 if(duration < 0){
55 me._showOrHideGo2Top();
56 return;
57 }
58 distance = destination - $container.scrollTop();
59 step = distance / duration * 10;
60 me._smoothScrollTime = setTimeout(function(){
61 if(!isNaN(parseInt(step, 10))) {
62 $container.scrollTop($container.scrollTop() + step);
63 me._smoothScroll(duration - 10);
64 }else{
65 me._showOrHideGo2Top();
66 }
67 }, 10);
68 return me;
69 },
70 _showOrHideGo2Top: function(){
71 var me = this,
72 $go2Top = me._go2Top;
73 if(me._container.scrollTop() > me._scrollTop){
74 $go2Top.show();
75 }else{
76 $go2Top.hide();
77 }
78 return me;
79 }
80 };
81 window.SmoothScroll = SmoothScroll;
82 })(jQuery, this);
在线演示