萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現果凍抖動動畫效果完整代碼解析

效果預覽與核心原理

利用 jQuery .animate() 串聯多個關鍵幀,透過寬度、高度、邊距、透明度的快速變化,模擬果凍般的彈性抖動效果。核心 CSS:position:relative 或 absolute 配合 margin-left 位移。

完整 HTML 結構

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
.test {
    margin: 10px 0;
    background-color: #7DBB00;
    height: 150px;
    border: 1px solid #ccc;
    border-radius: 10px;
    opacity: 0.8;
    width: 900px; /* 初始寬度 */
}
</style>
</head>
<body style="background:#e8e8e8;">
<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>
<script src="jquery.min.js"></script>
<script>
// 動畫邏輯見下方
</script>
</body>
</html>

jQuery 動畫核心代碼

$(function() {
    $('.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
            }, 200);
        }
    );
});

關鍵技術點解析

  • .stop(true):清空動畫隊列並跳至當前動畫結束狀態,防止快速進出導致動畫疊加抖動。
  • 鏈式 animate:依序執行多個動畫,形成關鍵幀序列。
  • marginLeft 負值:配合寬度變化產生「左右抖動」視覺效果。
  • opacity 漸變:增強立體感與層次感。

擴展建議

  1. 提取動畫參數為配置物件,支援自訂幅度、時長、緩動函數。
  2. 使用 CSS3 @keyframes + animation 替代 JS 動畫,效能更佳(GPU 加速)。
  3. 添加 will-change: transform, opacity 提升渲染效能。
copyright © 萬盛學電腦網 all rights reserved