內容很長的頁面,通常會在底部放一個返回頂部的錨點連結。純 HTML 就能做到(一個 href="#top" 即可),但缺點是跳躍太突然,使用者常常一時搞不清自己到了哪裡。本文示範如何加上 JavaScript,做出平滑滑動的返回頂部效果,體感舒適很多。
「TOP」連結一般放在頁面底部,點一下就能回到頂端,節省使用者滾動的時間。但真正的痛點是:使用者往往還沒看到底部就想離開了。
當頁面超過兩屏,只看了第一屏的人不想繼續往下,此時 TOP 連結還在第二屏之後。他通常會有三種反應:
也就是說,把返回頂部按鈕只放在頁尾,等於放棄了很大一部分需要它的使用者。以下三種方案依序改善這個問題。
最原始的做法,在頁面中段也放幾個錨點。但純錨點跳躍生硬,所以我們用腳本加上緩衝滑動效果。
HTML:
<a id="gototop" href="javascript:void(0);" onclick="goTop();return false;">Top of Page</a>
JavaScript:以 jQuery 為例,本質上就是利用 animate 對 scrollTop 做動畫:
function goTop() {
$('html, body').animate({ scrollTop: 0 }, 400);
}
關鍵細節是同時選 html 與 body,因為不同瀏覽器對 document 捲動高度的實作並不一致。
這樣使用者從頁面中段也能回到頂部,不必先滑到底。
HTML:
<a href="#top" id="gototop">Top of Page</a>
CSS:用 position: fixed 固定在右下角,並先隱藏起來。
#gototop {
display: none;
position: fixed;
right: 5px;
bottom: 5px;
color: green;
font-weight: bold;
text-decoration: none;
border: 1px solid green;
background: Lightgreen;
padding: 10px;
}
#gototop:hover { text-decoration: underline; }
MooTools 版本:需要 MooTools Core,另外還要 More 裡的 Fx.Scroll.js 與 Fx.SmoothScroll.js。
window.addEvent('domready', function() {
new SmoothScroll({ duration: 700 });
var go = $('gototop');
go.set('opacity', '0').setStyle('display', 'block');
window.addEvent('scroll', function(e) {
if (Browser.Engine.trident4) {
go.setStyles({
'position': 'absolute',
'bottom': window.getPosition().y + 10,
'width': 100
});
}
go.fade((window.getScroll().y > 300) ? 'in' : 'out');
});
});
這裡的 Browser.Engine.trident4 判斷是為了避開 IE6——它並不支援 position: fixed,只能退而求其次用 absolute 搭配捲動位置補償。
另一種做法是不寫死 HTML,而是用腳本動態產生 TOP 元素,並在捲過 80% 頁面高度時才淡入:
if (!Browser.Engine.trident4) {
window.addEvent((Browser.Engine.trident ? 'load' : 'domready'), function() {
var target_opacity = 0.64;
new Element('span', {
'id': 'back-to-top',
'styles': {
opacity: target_opacity,
display: 'none',
position: 'fixed',
bottom: 0,
right: 0,
cursor: 'pointer'
},
'text': 'back to top',
'tween': {
duration: 200,
onComplete: function(el) {
if (el.get('opacity') == 0) el.setStyle('display', 'none');
}
},
'events': {
'click': function() {
// location.hash 可讀寫頁面的錨點值
if (window.location.hash) {
window.location.hash = '#top';
} else {
window.scrollTo(0, 0);
}
}
}
}).inject(document.body);
window.addEvent('scroll', function() {
var visible = window.getScroll().y > (window.getSize().y * 0.8);
if (visible == arguments.callee.prototype.last_state) return;
if (Fx && Fx.Tween) {
if (visible) $('back-to-top').fade('hide').setStyle('display', 'inline').fade(target_opacity);
else $('back-to-top').fade('out');
} else {
$('back-to-top').setStyle('display', (visible ? 'inline' : 'none'));
}
arguments.callee.prototype.last_state = visible;
});
});
}
最後那段 last_state 的判斷值得留意:它記錄上一次的顯示狀態,狀態沒變就直接 return,避免捲動過程中重複觸發淡入淡出動畫。這是很多類似插件都會用到的效能技巧。
搭配 ScrollTo 插件可以獲得平滑的錨點滾動:
// plugin
jQuery.fn.topLink = function(settings) {
settings = jQuery.extend({ min: 1, fadeSpeed: 200 }, settings);
return this.each(function() {
var el = $(this);
el.hide(); // 預先隱藏,避免使用者忘記設定時閃一下
$(window).scroll(function() {
if ($(window).scrollTop() >= settings.min) {
el.fadeIn(settings.fadeSpeed);
} else {
el.fadeOut(settings.fadeSpeed);
}
});
});
};
// 使用方式
$(document).ready(function() {
$('#gototop').topLink({ min: 400, fadeSpeed: 500 });
$('#gototop').click(function(e) {
e.preventDefault();
$.scrollTo(0, 300);
});
});
要注意的是,這個版本在 Internet Explorer 上會失效,因為 IE 對 CSS position: fixed 的支持有問題。一個粗糙的補救方式是偵測 IE 後改用 absolute 定位,並在每次捲動時重新計算 top:
jQuery.fn.topLink = function(settings) {
settings = jQuery.extend({ min: 1, fadeSpeed: 200, ieOffset: 50 }, settings);
return this.each(function() {
var el = $(this);
el.css('display', 'none');
$(window).scroll(function() {
if (!jQuery.support.hrefNormalized) {
el.css({
'position': 'absolute',
'top': $(window).scrollTop() + $(window).height() - settings.ieOffset
});
}
if ($(window).scrollTop() >= settings.min) {
el.fadeIn(settings.fadeSpeed);
} else {
el.fadeOut(settings.fadeSpeed);
}
});
});
};
如果頁面不長,方案一足矣;若是典型的長篇內容頁,方案二或三無論在體驗還是轉換率上都明顯更好,因為它把「返回頂部」從一個埋在頁尾的補救措施,變成了一路陪伴使用者的工具。實作時記得兩件事:加上 stop() 或狀態判斷避免動畫堆疊,以及為不支援 fixed 的舊版 IE 準備退路。