圖片列表要突顯「目前看到哪一張」,最直覺的做法不是放大,而是把其他項目的透明度壓低。用 jQuery 的 fadeTo() 兩個事件就能完成,效果乾淨又不搶戲。
https://hovertree.com/texiao/jquery/1.htm
<!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>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery突出圖片列表中鼠標經過項 - 何問起</title><base target="_blank" />
<style type="text/css">
a {color:white;}
body{background:#000;}
body,div,ul,li,img{padding:0;margin:0; border:0; list-style:none;}
.hovertreebox{width:630px; border:1px solid #ccc; margin:10px auto; overflow:hidden; padding:10px 0 0 10px;}
.hovertreebox li{width:200px; height:186px; float:left; margin-right:10px; margin-bottom:10px; cursor:pointer;}
</style>
<script type="text/javascript" src="https:///keleyi/pmedia/jquery/jquery-1.11.2.min.js"></script>
<script type="text/javascript">
$(function(){
$('.hovertreebox li').mouseover(function (e) {
$(this).siblings().stop().fadeTo(500,0.4);
});
$('.hover'+'treebox li').mouseout(function (e) {
$(this).siblings().stop().fadeTo(500,1);
});
})
</script>
</head>
<body>
<div style="color:white">jQuery突出圖片列表中鼠標經過項
<br /><a href="https://hovertree.com">首頁</a> <a href="https://hovertree.com/hvtart/bjae/7f408b3a6bf8a433.htm">原文</a> <a href="https://hovertree.com/texiao/">更多特效</a></div>
<div class="hovertreebox" id="hovertreelist">
<ul>
<li><img src="https://hovertree.com/texiao/jquery/1/images/01.jpg" width="200" height="186" /></li>
<li><img src="https://hovertree.com/texiao/jquery/1/images/02.jpg" width="200" height="186" /></li>
<li><img src="https://hovertree.com/texiao/jquery/1/images/03.jpg" width="200" height="186" /></li>
<li><img src="https://hovertree.com/texiao/jquery/1/images/04.jpg" width="200" height="186" /></li>
<li><img src="https://hovertree.com/texiao/jquery/1/images/05.jpg" width="200" height="186" /></li>
<li><img src="https://hovertree.com/texiao/jquery/1/images/06.jpg" width="200" height="186" /></li>
</ul>
</div>
<div style="text-align:center;margin:50px 0; font:normal 14px/24px 'MicroSoft YaHei';color:white;">
<p>適用浏覽器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗.</p>
<p>來源:<a href="https://hovertree.com/" target="_blank">HoverTree</a></p>
</div>
</body>
</html>
滑鼠移進某個 li 時,用 $(this).siblings() 抓到「同一層的其他兄弟項目」,把它們的透明度動畫到 0.4;移出時再全部拉回 1。被指向的那一張永遠維持不透明,視線自然被牽引過去。
這裡有兩個容易忽略的細節。siblings() 不包含自己,所以不需要額外排除;stop() 則用來清掉尚未播完的動畫佇列,否則快速掃過多張圖會出現透明度忽明忽暗的追車現象。
fadeTo(duration, opacity) 是專門改透明度的語法糖,內部等同於對 opacity 做動畫。若你還想同時改變尺寸或位置,就要改用 animate({opacity:0.4, transform:"scale(0.95)"}, 500) 這種寫法。第一個參數 500 是毫秒,代表動畫長度。
單純放大會撐破 li 的固定寬高,造成浮動錯位;若真要放大,得搭配 transform:scale() 加上 z-index 與 position:relative,複雜度立刻上升。透明度方案的好處是零版面影響,任何尺寸的圖片牆都能直接套用。
適用瀏覽器:IE8、360、FireFox、Chrome、Safari、Opera、傲游、搜狗、世界之窗。
來源:HoverTree