DIV CSS 佈局教程網

用 jQuery animate 實作果凍般的抖動放大效果
編輯:JavaScript綜合知識     

滑鼠移入時,方塊先膨脹再回縮、最後定住,看起來像果凍一樣有彈性。這個效果的祕密很單純:把連續幾段 animate() 串接起來,讓尺寸在「大一點 → 小一點 → 剛好」之間來回一次。

CSS 部分

.test {
    margin: 10px 0;
    background-color: #7DBB00;
    height: 150px;
    border: 1px #ccc solid;
    -moz-border-radius: 5px;
    -khtml-border-radius: 5px;
    -webkit-border-radius: 5px;
    border-radius: 10px;
    opacity: 0.8;
}

HTML 結構

<div style="margin:50px auto; width:900px; overflow:visible;">
  <div id="test_01" class="test"></div>
  <div id="test_02" class="test"></div>
  <div id="test_03" class="test"></div>
  <div id="test_04" class="test"></div>
  <div id="test_05" class="test"></div>
  <div id="test_06" class="test"></div>
</div>

動畫腳本

$('.test').hover(function () {
    $(this)
        .animate({ width: 920, height: 170, marginLeft: -20, opacity: 0.8 }, 100)
        .animate({ width: 910, height: 160, marginLeft: -10, opacity: 0.9 }, 100)
        .animate({ width: 920, height: 170, marginLeft: -20, opacity: 1   }, 100);
}, function () {
    $(this).stop(true).animate({
        width: 900, height: 150, marginLeft: 0, opacity: 0.8
    }, 100);
});

三個關鍵細節

1. marginLeft 為什麼是負值?方塊預設靠左對齊,寬度變大時會往右撐開,視覺重心就歪了。給一個負的左邊界,等於把它往左拉回中心位置。用負值的一半(宽度增加 20px,marginLeft 設 -10px)可以讓擴展看起來是從中央均勻向外。margin: 0 auto 這種置中寫法在動畫過程中反而不好控制,因此這裡改用絕對數值。

2. stop(true) 的作用。滑鼠快速掠過多個方塊時,動畫會堆疊排隊,方塊會持續抖個不停。stop(true) 會清空佇列並停止當前動畫,讓元素立刻回應新的滑鼠狀態。

3. 為什麼是三段?三段的值是「920 → 910 → 920」,也就是先衝過頭、再收一點、最後補滿,這種「過衝再收斂」正是彈性感的來源。若只寫一段,看起來就是普通的放大,沒有果凍味。

現代寫法對照

如果今天重寫這個效果,用 CSS transition 會更流暢,也不佔用主執行緒:

.test {
    transition: all .3s cubic-bezier(.34, 1.56, .64, 1);
}
.test:hover {
    transform: scale(1.05);
}

cubic-bezier(.34, 1.56, .64, 1) 這條曲線的第二控制點超過了 1,同樣會產生過衝回彈的手感,一行就搞定,而且不會因為動畫排隊而卡住。jQuery 的 animate() 無法動畫 transform,這也是它逐漸被 CSS 動畫取代的原因之一。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved