DIV CSS 佈局教程網

jQuery animate() 實作:點擊觸發元素移動與透明度漸變
編輯:JQuery特效代碼     

animate() 是讓靜態版面「活起來」最直接的工具。只要告訴它「最終要變成什麼樣子」,它就會自動補上中間的每一格畫面。

一、基本結構

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <title>animate 移動與漸變</title>
  <script src="js/jquery.js"></script>
<style>
body{font-family:"微軟雅黑";width:980px;margin:0 auto;text-align:center;}
.box{width:300px;height:300px;background:green;border:1px solid #e6e6e6;
     margin-top:50px;line-height:200px;position:absolute;}
button{border:none;background:green;width:100px;height:50px;line-height:50px;
       color:#fff;font-size:16px;margin-top:50px;}
</style>
</head>
<body>
  <button>點擊開始動畫</button>
  <div class="box"></div>

  <script>
  $(document).ready(function(){
    $("button").click(function(){
      var div = $(".box");
      div.animate({height:'200px', opacity:'0.4'}, "slow");
      div.animate({width:'200px',  opacity:'0.8'}, "slow");
      div.animate({height:'100px', opacity:'0.4'}, "slow");
      div.animate({width:'100px',  opacity:'0.8'}, "slow");
      div.animate({right:'100px',  opacity:'0.8'}, "slow");
      div.animate({bottom:'100px', opacity:'0.8'}, "slow");
      div.animate({left:'100px',   opacity:'0.8'}, "slow");
      div.animate({top:'100px',    opacity:'0.8'}, "slow");
    });
  });
  </script>

二、另一組對照:先放大再縮小

$(document).ready(function(){
  $("button").click(function(){
    var div = $(".box");
    div.animate({height:'300px', opacity:'0.4'}, "slow");
    div.animate({width:'300px',  opacity:'0.8'}, "slow");
    div.animate({height:'100px', opacity:'0.4'}, "slow");
    div.animate({width:'100px',  opacity:'0.8'}, "slow");
  });
});

把兩段一起看就能發現:只要改動的屬性與目標值不同,做出來的效果就完全不同,而程式結構一模一樣。這正是 animate 的威力——你負責描述結果,它負責過程。

三、兩個一定要知道的眉角

1. 定位屬性需要 position 配合。top/right/bottom/left 要能生效,元素的 position 不能是 static。範例中 .box 設了 position:absolute,位移才有意義。實務上用 relative 也常見。

2. animate 只能動「數值型」屬性。寬高、邊距、透明度、位移都可以;color 這類顏色值原生 animate 不支援,需要 color animation 插件或改用 CSS transition。

Tips 整理

  • 用 var div = $(".box") 先把要操縱的元素存成變數,後面反覆使用更省事,也避免重複查詢 DOM。
  • duration 可寫 "slow"/"fast"/"normal",或直接給毫秒數。
  • 其餘的部分,就實際敲一次、看一次畫面,理解會比讀十遍說明書更快。
XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved