// 第一次點擊:正常向上移動 300px
// 第二次點擊:無動畫、無反應
$(".page").stop().animate({top: "-300px"}, 800, 'easeInOutExpo');
top: "-300px" 是**絕對值**,表示元素頂部相對父元素頂部的目標位置。第一次動畫後,元素已位於 top: -300px;第二次動畫目標同樣是 -300px,**位移距離為 0**,故無動畫。
// "+=" 或 "-=" 表示相對當前位置增減
$(".page").stop().animate({top: "-=300px"}, 800, 'easeInOutExpo');
每次點擊在**當前位置基礎上**再向上移動 300px,完美解決連續點擊動畫。
function down() {
var page_h = $(".page").height(); // 687 (無單位數值)
var page_top = parseInt($(".page").css("top")); // 0 (去掉 px)
var move = page_top - page_h; // 計算目標位置
$(".page").stop().animate({top: move}, 800, 'easeInOutExpo');
}
關鍵點:
.height() 返回數值(無單位)。.css("top") 返回帶 px 字符串,需 parseInt 轉數值。top,計算新目標位置。.stop([clearQueue], [jumpToEnd])
// clearQueue: true 清除動畫隊列,false(默認) 僅停止當前動畫
// jumpToEnd: true 立即完成當前動畫, false(默認) 停留在當前狀態
// 常用組合
.stop(true, true) // 清隊列+跳到終點,防止排隊
.stop(true, false) // 清隊列+停當前幂,平滑啟動新動畫
$('.page').on('click', function() {
const $page = $(this);
const currentTop = parseInt($page.css('top')) || 0;
const step = $page.height(); // 或固定值 300
$page.stop(true, false).animate({top: currentTop - step}, 800, 'easeInOutExpo');
});
.page {
transition: top 0.8s cubic-bezier(0.4, 0, 0.2, 1); /* easeInOutExpo 近似 */
}
.page.move-up { top: -300px; } /* 或配合 JS 切換類名 */
將動畫交給瀏覽器合成器,主線程零負擔,性能最優。