圖庫展示頁常有這樣的巧思:滑鼠移入某張圖片時,它會從灰階漸變為彩色。這種效果看起來相當有質感。本文將示範如何用 jQuery 的 hover、find、css 等方法實作它。
效果原理
做法是:在滑鼠移入時,把圖片的 URL 設為連結的背景,再讓原本的 img 逐漸淡出,於是背景圖就「浮」了出來;移出時再讓圖片淡入回來。透過 CSS 與 jQuery 的 fadeTo 動畫搭配,就能得到平滑的漸顯過渡。
完整程式碼
代碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>超個性的感應鼠標懸停圖片色彩漸顯效果</title>
<meta http-equiv="content-type" content="text/html;charset=gb2312">
<style type="text/css">
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; -moz-border-radius: 3px; -khtml-border-radius: 3px; -webkit-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; } /*--Used to crop image--*/
ul.gallery li a.thumb:hover { background: #333; } /*--Hover effect for browser with js turned off--*/
ul.gallery li h2 { font-weight: normal; margin: 0; padding: 10px; background: #f0f0f0; border-top: 1px solid #fff; } /*--Subtle bevel effect--*/
ul.gallery li a { text-decoration: none; color: #777; display: block; font-size: 140%; }
</style>
<script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("ul.gallery li").hover(function() { //On hover...
var thumbOver = $(this).find("img").attr("src"); //Get image url and assign it to 'thumbOver'
$(this).find("a.thumb").css({'background' : 'url(' + thumbOver + ') no-repeat center bottom'});
$(this).find("span").stop().fadeTo('normal', 0 , function() { $(this).hide() });
} , function() { //on hover out...
$(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>
關鍵在於 hover 的兩個回呼:移入時把 img 淡出並以背景圖呈現彩色版本,移出時再淡入還原。stop() 的加入則能避免連續滑動時動畫堆疊。掌握這個技巧,就能為你的圖庫加上靈動的互動質感。希望本文對你的 jQuery 開發有所幫助。