圖片 hover 時向上捲走、下方浮出說明文字——這個效果看起來花俏,實際程式碼只有十幾行。思路對了,一切都很簡單。
<ul class="list"> <li><img src="images/10.jpg" alt="" /><a href="#"><span>1</span></a></li> <li><img src="images/11.jpg" alt="" /><a href="#"><span>2</span></a></li> <li><img src="images/12.jpg" alt="" /><a href="#"><span>3</span></a></li> <li><img src="images/13.jpg" alt="" /><a href="#"><span>4</span></a></li> <li><img src="images/10.jpg" alt="" /><a href="#"><span>5</span></a></li> <li><img src="images/11.jpg" alt="" /><a href="#"><span>6</span></a></li> <li><img src="images/12.jpg" alt="" /><a href="#"><span>7</span></a></li> <li><img src="images/13.jpg" alt="" /><a href="#"><span>8</span></a></li> </ul>
* { margin: 0; padding: 0; }
.list {
width: 640px;
margin: 100px auto;
border: 1px solid #ddd;
overflow: hidden;
}
.list li {
float: left;
width: 150px; height: 80px;
overflow: hidden;
list-style: none;
margin: 5px;
display: inline;
position: relative;
}
.list li img {
float: left;
width: 150px; height: 80px;
border: none;
}
.list li a {
position: absolute;
left: 0; top: 0;
width: 150px; height: 0;
background: #999;
margin-top: 40px; /* 初始藏在圖片下方 */
display: inline;
text-align: center;
line-height: 80px;
overflow: hidden;
color: #fff;
text-decoration: none;
}
這裡的關鍵是 li 設為 position: relative 且 overflow: hidden,讓絕對定位的 a 可以被裁切;再用 margin-top: 40px 把它藏在可视范围外。
$(function () {
$('.list li').hover(function () {
// 滑入:先停止既有動畫,避免連點造成動畫堆疊
$(this).children('a,img').stop();
$(this).children('img').stop().animate({ 'marginTop': 40, 'height': 0 }, 200, function () {
$(this).siblings('a').stop().animate({ 'height': 80, 'marginTop': 0 }, 200);
});
}, function () {
// 滑出:反向播放
$(this).children('a,img').stop();
$(this).children('a').stop().animate({ 'height': 0, 'marginTop': 40 }, 200, function () {
$(this).siblings('img').stop().animate({ 'marginTop': 0, 'height': 80 }, 200);
});
});
});
.stop() 是靈魂:滑鼠快速進出時,動畫會一條條排在佇列裡等著播放,畫面看起來就是卡頓又落後。stop() 會清掉佇列,讓新的動畫立刻接管。若要在中途平順過渡,可寫成 .stop(true, true)。把 animate 的時間從 200 調成 400 左右,節奏會更從容;想加上延遲感,也可以在回呼前插入 .delay(100)。就這幾行,效果立刻不一樣。