騰訊微博當年有一個很經典的互動:把滑鼠移到天氣區域上,內容會像抽屜一樣從左側平滑滑出。本文將帶大家用 jQuery 復刻這個效果,製作出一個滑出式的每日天氣提示框。
默認情況下,頁面只顯示一個「城市」入口。當滑鼠移上去時,一個藏在其左側的天氣內容面板會以動畫方式滑出;滑鼠移開後,面板又會平滑收回。整個過程流暢自然,這一切都要歸功於 jQuery 的 animate 方法。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>仿騰訊微博的每日天氣效果</title>
<style>
.weather{ width:500px;height:100px;margin:0 auto; position:relative;color:#fff;text-align:center; overflow:hidden; }
.weather_main{ width:99px;border-right:solid 1px #fff; float:left;background:#F03;text-align:center; position:relative;z-index:2; }
.weather_main strong{ line-height:100px; }
.alert{ width:400px;height:100px;position:absolute; left:-400px;top:0;background:#F03; }
</style>
<script src="jquery-1.6.2.min.js"></script>
<script>
$(document).ready(function(){
$(".weather_main").hover(function(){
$(".alert").animate({left:"100px"},1000);
},function(){
$(".alert").animate({left:"-400px"},1000);
});
})
</script>
</head>
<body>
<div class="weather">
<div class="weather_main">
<strong><a>深圳</a></strong>
</div>
<div class="alert">
<p>如果雲知道,多想涼風來做伴~</p>
</div>
</div>
</body>
</html>
關鍵在於將隱藏面板的初始 left 設為 -400px,讓它藏在容器左側的可視範圍之外。滑鼠移入時,用 animate 把 left 動畫到 100px,面板便滑了出來;移出時再動畫回 -400px 收回。外層容器設定 overflow:hidden,能確保面板在隱藏時不會溢出顯示,營造出「抽屜」般的視覺效果。
希望本文所述能對大家的 jQuery 程序設計有所幫助。