幫朋友做的小效果:頁面上疊著四張不同顏色的卡片,滑鼠移入哪一張,它就放大浮到最上層;移出後平滑回到原本的大小與位置。需求很單純,只有四個元素,所以直接把尺寸寫死,不必動用 CSS3 動畫。
四張卡片都用絕對定位堆在同一個左上角,靠 z-index 決定前後關係,再用 top 做出微微錯落的層疊感。
<style>
body{ z-index: 0; width: 100%; min-height: 400px; }
.pages{ position: absolute; }
.current{ position: absolute; z-index: 12 !important; left: 0px !important; }
.page1{ background-color: #a5cfff; z-index: 1; width: 300px; height:280px; top: 100px; left: 0px; }
.page2{ background-color: #b1ca54; z-index: 2; width: 250px; height:270px; top: 160px; left: 0px; }
.page3{ background-color: #c2c6c9; z-index: 3; width: 200px; height:260px; top: 220px; left: 0px; }
.page4{ background-color: #ef9e9c; z-index: 4; width: 150px; height:250px; top: 250px; left: 0px; }
</style>
放大時先加上 current 類別取得最高層級,並把原始的 inline style 存進自訂屬性 styleold 以備還原;接著用 animate 在 600ms 內放大到 400×400,最後再用 30ms 把透明度補到 1,形成一個細微的收尾。
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$(function(){
// 增長
function increase($div,e){
var style = $div.attr("style");
$div.addClass("current").attr("styleold",style);
$div.stop();
$div.animate({
opacity:0.9,
width:"400px",
height: "400px",
top: "100px",
left: "0px"
},600)
.animate({ opacity:1.0 },30);
e.stopPropagation();
return false;
};
// 還原
function resize(e){
var $page1 = $(".current.page1");
$page1.stop();
$page1.animate({
opacity:1.0, width:"300px", height: "280px", top: "100px", left: "0px"
},600,null,function(){
$page1.removeClass("current").attr("style","");
});
var $page2 = $(".current.page2");
$page2.stop();
$page2.animate({
opacity:1.0, width:"250px", height: "270px", top: "160px", left: "0px"
},600,null,function(){
$page2.removeClass("current").attr("style","");
});
var $page3 = $(".current.page3");
$page3.stop();
$page3.animate({
opacity:1.0, width:"200px", height: "260px", top: "220px", left: "0px"
},600,null,function(){
$page3.removeClass("current").attr("style","");
});
var $page4 = $(".current.page4");
$page4.stop();
$page4.animate({
opacity:1.0, width:"150px", height: "250px", top: "250px", left: "0px"
},600,null,function(){
$page4.removeClass("current").attr("style","");
});
e.stopPropagation();
return false;
};
$(".pages").unbind("mouseover").bind("mouseover",function(e){
return increase($(this),e);
}).unbind("mouseout").bind("mouseout",function(e){
return resize(e);
});
$("body").click(function(e){
return resize(e);
});
});
</script>
<div class="pages page1">page1</div>
<div class="pages page2">page2</div>
<div class="pages page3">page3</div>
<div class="pages page4">page4</div>
<div style="background-color: #a5cfff;">
<button id="button1">第一頁</button>
<button id="button2">第2頁</button>
<button id="button3">第3頁</button>
<button id="button4">第4頁</button>
</div>
三個實作重點:stop() 避免快速滑動時動畫堆疊;還原動畫放在 complete 回呼裡移除 class,確保動畫跑完才清除內聯樣式;stopPropagation() 阻止事件冒泡到 body,否則放大後立刻被 body 的點擊事件還原。
若要推廣成任意數量、任意尺寸的版本,把這些寫死的數值改讀 data-* 屬性,或直接改用 CSS transform 的 scale() 搭配 transition,程式碼會短很多。