DIV CSS 佈局教程網

用 jQuery 實現鼠標懸停小圖顯示大圖
編輯:JavaScript綜合知識     

電商與圖廊網站常有"懸停小圖預覽大圖"的需求。本文用一個完整實例,講解如何用 jQuery 實現這一效果,涉及圖片與鼠標事件的操作技巧。

核心思路是:把大圖地址和名稱存在小圖的自定義屬性上,鼠標移入時讀取並顯示大圖、移出時隱藏。

代碼如下: <html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
</head>
<style type="text/css">
li{list-style:none;float:left;margin-left:10px;}
</style>
<script type="text/javascript" src="jquery-1.8.2.min.js"></script>
<script type="text/javascript">
var data = {
"images/11_s.jpg":["images/11_b.jpg","美人1"],
"images/22_s.jpg":["images/22_b.jpg","美人2"]
};
$(function(){
$.each(data,function(key,value){
$("div").last().hide();
var smallPath = $("<img src='" + key + "' />").css({"margin":"5px","padding":"2px","border":"1px solid #000"});
bigImgPath = smallPath.attr("bigMapPath",value[0]);
bigImgName = smallPath.attr("bigMapName",value[1]);
$("div").first().append(smallPath);
smallPath.mouseover(function(){
$("div").last().fadeIn("fast");
$("#show").attr("src",$(this).attr("bigMapPath"));
$("#imgTitle").text($(this).attr("bigMapName"));
});
smallPath.mouseout(function(){
$("div").last().fadeOut("fast");
});
});
});
</script>
<body>
<div></div>
<div>
<img id="show" src="" />
</div>
</body>
</html>

這段代碼先用一個 data 對象存儲小圖、大圖與名稱的映射關係,再通過 each 遍歷生成小圖並綁定 mouseover / mouseout 事件。懸停時用 fadeIn 淡入大圖並更新 src 與標題,移出時 fadeOut 淡出。這種做法既省去了大量重複的 HTML,也讓後續擴展圖片列表變得非常容易。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved