效果體驗:https://hovertree.com/texiao/mobile/6/
在 PC 上用 scrollTop() 做返回頂部動畫很簡單,但同一段程式碼搬到行動端往往就失效——動能不順、卡頓,甚至完全沒反應。
根本原因是行動裝置的 scroll 事件觸發頻率低得多,很可能整個過程中都沒有偵測到 scrollTop() <= 0 的瞬間,於是收尾的程式碼永遠不會執行。解法是改用「移動次數」來判斷何時停止,不要只依賴位置。
<style>
#tophovertree{display:block;position:fixed;width:36px;height:36px;right:20px;bottom:20px;
cursor:pointer;background-image:url(https://hovertree.com/texiao/mobile/6/tophovertree.gif);
opacity:0.9;display:none}
</style>
<span id="tophovertree" title="返回頂部"></span>
<script src="https://hovertree.com/texiao/mobile/6/topHovertree.js"></script>
<script>
$(function () { initTopHoverTree("tophovertree", 30, 30, 10); })
</script>
function initTopHoverTree(hvtid, times, right, bottom) {
$("#" + hvtid).css("right", right).css("bottom", bottom);
$("#" + hvtid).on("click", function () { goTopHovetree(times); })
$(window).scroll(function () {
if ($(window).scrollTop() > 268) {
$("#" + hvtid).fadeIn(100);
} else {
$("#" + hvtid).fadeOut(100);
}
});
}
function goTopHovetree(times) {
if (!!!times) { $('body').scrollTop(0); return; }
var sh = $('body').scrollTop(); // 移動總距離
var inter = 13.333; // 每次移動間隔(毫秒)
var forCount = Math.ceil(times / inter); // 移動次數
var stepL = Math.ceil(sh / forCount); // 移動步長
var timeId = null;
function aniHovertree() {
!!timeId && clearTimeout(timeId);
timeId = null;
// 行動端以「剩餘次數」為主判斷,因為 scroll 事件觸發不頻繁
if ($('body').scrollTop() <= 0 || forCount <= 0) {
$('body').scrollTop(0);
return;
}
forCount--;
sh -= stepL;
$('body').scrollTop(sh);
timeId = setTimeout(function () { aniHovertree(); }, inter);
}
aniHovertree();
}
關鍵設計有三點:先算出總距離與期望耗時,反推「需要移動幾次」與「每次步長」;再用 setTimeout 自 recurse 逐步位移;最後以 forCount <= 0 作為主要終止條件,位置判斷只當輔助。如此一來即使 scroll 事件沒觸發,動畫也能確實收尾並歸零。這段邏輯在 PC 上同樣適用,可作為跨裝置的通用寫法。