圖片列表中,滑鼠移入某張圖片 → 該圖保持不透明度 1,其餘同層圖片淡化至 0.4;滑鼠移出 → 全部恢復不透明度 1。視覺聚焦感強,常用於商品展示、作品集畫廊。
<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>jQuery 圖片懸停高亮</title>
<style>
.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; list-style:none; }
</style>
<script src="jquery-1.11.2.min.js"></script>
<script>
$(function() {
$('.hovertreebox li').mouseover(function() {
$(this).siblings().stop().fadeTo(500, 0.4);
});
$('.hovertreebox li').mouseout(function() {
$(this).siblings().stop().fadeTo(500, 1);
});
});
</script>
</head>
<body>
<div class="hovertreebox" id="hovertreelist">
<ul>
<li><img src="/images/01.jpg" width="200" height="186" /></li>
<li><img src="/images/02.jpg" width="200" height="186" /></li>
<li><img src="/images/03.jpg" width="200" height="186" /></li>
<li><img src="/images/04.jpg" width="200" height="186" /></li>
<li><img src="/images/05.jpg" width="200" height="186" /></li>
<li><img src="/images/06.jpg" width="200" height="186" /></li>
</ul>
</div>
</body></html>
.siblings() 選取同層其他 li,排除自身。.stop() 停止當前動畫佇列,防止快速進出導致動畫疊加、延遲。.fadeTo(duration, opacity) 直接動畫至目標不透明度,比 animate({opacity}) 更簡潔。overflow:hidden 配合浮動佈局,自動換行排列。
.gallery { display:flex; flex-wrap:wrap; gap:10px; }
.gallery img { width:200px; height:186px; transition:opacity 0.5s ease; }
.gallery:hover img { opacity:0.4; }
.gallery img:hover { opacity:1; }
利用 :hover 父層選中所有子圖降低不透明度,再以子元素 :hover 覆蓋回 1,零 JS、效能極佳、支援觸控(需 @media (hover:hover) 包裹)。
alt 說明。.gallery a:focus img、.gallery a:focus-within img。filter:grayscale(1))。