本文介紹了一些關於JQuery實現動畫效果的語法和案例
jQuery 動畫 - animate() 方法
jQuery animate() 方法用於創建自定義動畫。
語法:
$(selector).animate({params},speed,callback);
必需的 params 參數定義形成動畫的 CSS 屬性。
可選的 speed 參數規定效果的時長。它可以取以下值:"slow"、"fast" 或毫秒。
可選的 callback 參數是動畫完成後所執行的函數名稱。
下面的例子演示 animate() 方法的簡單應用;它把 <div> 元素移動到左邊,直到 left 屬性等於 250 像素爲止:
實例
$("button").click(function(){ $("div").animate({left:'250px'}); });
提示:默認地,所有 HTML 元素都有一個靜態位置,且無法移動。
如需對位置進行操作,要記得首先把元素的 CSS position 屬性設置爲 relative、fixed 或 absolute!
jQuery animate() - 操作多個屬性
請注意,生成動畫的過程中可同時使用多個屬性:
實例
$("button").click(function(){ $("div").animate({ left:'250px', opacity:'0.5', height:'150px', width:'150px' }); });
提示:可以用 animate() 方法來操作所有 CSS 屬性嗎?
是的,幾乎可以!不過,需要記住一件重要的事情:當使用 animate() 時,必須使用 Camel 標記法書寫所有的屬性名,比如,必須使用 paddingLeft 而不是 padding-left,使用 marginRight 而不是 margin-right,等等。
同時,色彩動畫並不包含在覈心 jQuery 庫中。
如果需要生成顏色動畫,您需要從 jQuery.com 下載 Color Animations 插件。
jquery的animate方法可以自定義動畫,但是,只能針對數字類型的屬性,如大小,高度,透明度等。
對於非數字類型如顏色,則不支持動畫。所以,需要自行處理。
jqueryui 中增加個這個支持,可以供我們使用。
如果,只是需要顏色動畫,可以不必要加載所有的jqueryui 文件。只需要它的一部分。
有高人將其獨立出來了。
jquery.colorAnimations.js
<script type="text/javascript" src="jquery-1.7.2.min.js"></script>
<script type="text/javascript" src="jquery.colorAnimations.js"></script>
<div> <a href="javascript:void(0);" id="button">點擊這裏</a></div>
<textarea name="detail" cols="60" rows="5" id="detail"></textarea>
<script type="text/javascript">
$("#button").click(
function(){
flash(2,200);
}
);
function flash(total,speed)
{
total --;
if(total >= 0 )
{
$("#detail").animate({backgroundColor: "rgb(250,128,114)" }, speed,
function(){
$("#detail").animate({backgroundColor: "rgb(255,255,255)" }, speed,function(){flash(total,speed);});
}
);
}
}
</script>
jQuery animate() - 使用相對值
也可以定義相對值(該值相對於元素的當前值)。需要在值的前面加上 += 或 -=:
實例
$("button").click(function(){ $("div").animate({ left:'250px', height:'+=150px', width:'+=150px' }); });
jQuery animate() - 使用預定義的值
您甚至可以把屬性的動畫值設置爲 "show"、"hide" 或 "toggle":
實例
$("button").click(function(){ $("div").animate({ height:'toggle' }); });
jQuery animate() - 使用隊列功能
默認地,jQuery 提供針對動畫的隊列功能。
這意味着如果您在彼此之後編寫多個 animate() 調用,jQuery 會創建包含這些方法調用的“內部”隊列。然後逐一運行這些 animate 調用。
實例 1
隱藏,如果您希望在彼此之後執行不同的動畫,那麼我們要利用隊列功能:
$("button").click(function(){ var div=$("div"); 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"); });