在瀏覽網頁時常會看到這樣的效果:滑鼠移到某個區塊上,旁邊就會滑出一個額外的盒子。這種下拉展開的互動其實用 jQuery 的 animate 就能輕鬆做出來。
JavaScript 部分:
<script src="js/Jquery1.7.js"></script>
<script type="text/javascript">
$(function () {
$('div:eq(1)').css({ 'margin-top': '-=100px' });
$('div:first').mouseover(function () {
$('div:eq(1)').animate({'margin-top':'+=100px'});
})
$('div:first').mouseout(function () {
$('div:eq(1)').animate({ 'margin-top': '-=100px' });
})
})
</script>
HTML 部分:
<div style="width:600px;height:300px;overflow:hidden;">
<div style="background-color:#000;height:100px;"></div>
<div style="background-color:#eee;height:300px;"></div>
</div>
當滑鼠移動到盒子上時,上面就會滑出一個黑色的盒子;移開後又收回去。這裡的技巧是用外層容器的 overflow:hidden 把超出部分裁掉,再透過改變 margin-top 並搭配 animate 產生滑動動畫,就能做出乾淨俐落的展開效果。