<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head><meta charset="gb2312"><title>感應鼠標懸停圖片色彩漸顯效果</title>
<style>
ul.gallery { width:750px; list-style:none; margin:0; padding:0; }
ul.gallery li { float:left; margin:10px 0 10px 25px; padding:0; text-align:center; border:1px solid #ccc; border-radius:3px; display:inline; }
ul.gallery li a.thumb { width:336px; height:240px; border-bottom:1px solid #ccc; cursor:pointer; }
ul.gallery li span { width:336px; height:240px; overflow:hidden; display:block; }
ul.gallery li a.thumb:hover { background:#333; } /* JS 關閉時的降級樣式 */
ul.gallery li h2 { font-weight:normal; margin:0; padding:10px; background:#f0f0f0; border-top:1px solid #fff; }
ul.gallery li a { text-decoration:none; color:#777; display:block; font-size:140%; }
</style>
<script src="/js/jquery-1.4.2.min.js"></script>
<script>
$(document).ready(function() {
$("ul.gallery li").hover(function() {
// 移入
var thumbOver = $(this).find("img").attr("src"); // 取得圖片原始 src
$(this).find("a.thumb").css({ 'background': 'url(' + thumbOver + ') no-repeat center bottom' });
$(this).find("span").stop().fadeTo('normal', 0, function() { $(this).hide(); });
}, function() {
// 移出
$(this).find("span").stop().fadeTo('normal', 1).show();
});
});
</script>
</head>
<body>
<ul class="gallery">
<li>
<a href="#" class="thumb"><span><img src="/html/txdm_2/images/20100904/336240.jpg" alt=""></span></a>
<h2><a href="#">Sunflowa Media</a></h2>
</li>
</ul>
</body></html>
a.thumb 作為背景容器,span > img 作為前景圖層。初始顯示 img,背景預設無圖。find("img").attr("src") 取得原圖 URL。css('background', 'url(...)') 設定給 a.thumb,成為底層彩色圖。fadeTo('normal', 0) 將 span (含 img) 淡出至透明,完成時 hide() 移除佔位。fadeTo('normal', 1).show() 恢復前景圖層不透明度。a.thumb:hover { background:#333; }
若用戶關閉 JS,滑鼠移入仍顯示深灰背景,保留基本視覺回饋。
transition: opacity 0.3s + class 切換,完全移除 JS 動畫,效能更佳。IntersectionObserver 延遲載入圖片。touchstart/touchend 切換狀態。srcset、預載關鍵圖片。此範例展示 jQuery 「尋找元素 → 修改樣式 → 動畫過渡」的經典工作流。理解 hover、find、css、fadeTo、stop 協作細節,是掌握 jQuery 互動開發的關鍵基石。