這個範例示範如何讓六個導覽項在滑鼠移入時放大、移出時復原。程式跑起來後記得按 F5 重新整理,才能看到 jQuery 生效。
<div class="all"> <div class="m1" jquery1274844839136="1">標題1</div> <div class="m2" jquery1274844839136="2">標題2</div> <div class="m3" jquery1274844839136="3">標題3</div> <div class="m4" jquery1274844839136="4">標題4</div> <div class="m5" jquery1274844839136="5">標題5</div> <div class="m6" jquery1274844839136="6">標題6</div> </div> <div>進入之後才能看到效果!</div>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function () { myHide(); });
function myHide() {
// 逐一註冊 mouseover / mouseout
$(".m1").bind('mouseover', m1_mouseover);
$(".m1").bind('mouseout', m1_mouseout);
$(".m2").bind('mouseover', m2_mouseover);
$(".m2").bind('mouseout', m2_mouseout);
$(".m3").bind('mouseover', m3_mouseover);
$(".m3").bind('mouseout', m3_mouseout);
$(".m4").bind('mouseover', m4_mouseover);
$(".m4").bind('mouseout', m4_mouseout);
$(".m5").bind('mouseover', m5_mouseover);
$(".m5").bind('mouseout', m5_mouseout);
$(".m6").bind('mouseover', m6_mouseover);
$(".m6").bind('mouseout', m6_mouseout);
}
function m1_mouseover() {
$(".m1").animate({ width: "100px", height: "30px", fontSize:"22px" }, "fast");
}
function m1_mouseout() {
$(".m1").animate({ width: "70px", height: "20px", fontSize: "14px" }, "fast");
}
// m2 ~ m6 的處理函數與 m1 完全相同,只是換成各自的 class 選擇器
</script>
<style type="text/css">
.m1,.m2,.m3,.m4,.m5,.m6 {
width:70px; height:20px; background-color:#cccccc;
border: thin solid #9999ff; font-size:14px;
}
.all { width:80px; height:160px; text-align:center; }
</style>
原範例為六個項目各寫一對函數,總共十二個,其實完全沒有必要。用 class 屬性迴圈一次綁完即可:
$(function(){
$(".all div").hover(
function(){ $(this).stop(true).animate({width:"100px",height:"30px",fontSize:"22px"},"fast"); },
function(){ $(this).stop(true).animate({width:"70px",height:"20px",fontSize:"14px"},"fast"); }
);
});
加上 stop(true) 可以在動畫進行中被再次觸發時先中止上一段動畫,避免快速滑過時出現抖動。這是 jQuery 動畫寫作中值得養成习惯的細節。