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。
var div = $(".box") 先把要操縱的元素存成變數,後面反覆使用更省事,也避免重複查詢 DOM。"slow"/"fast"/"normal",或直接給毫秒數。