萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

jQuery 實現背景牆聚光燈效果(圖片懸停高亮)

效果描述

圖片牆初始半透明,鼠標懸停某圖片時該圖變不透明並加白邊突出,其他圖保持半透明;鼠標離開牆區域所有圖恢復全顯示。

完整實現代碼

<!DOCTYPE HTML>
<html><head>
<meta charset="utf-8">
<title>jQuery 背景牆聚光燈效果</title>
<script src="/jquery.js"></script>
<style>
body { background: black; color: white; font-family: georgia; }
.spotlightWrapper ul { list-style: none; margin: 0; padding: 0; }
.spotlightWrapper ul li { float: left; position: relative; }
.spotlightWrapper ul li a img { 
    width: 200px; 
    position: relative; 
    border: none; 
}
.spotlightWrapper ul li a img.active { 
    border: 4px solid white; 
    z-index: 1; 
    left: -4px; 
    top: -4px; 
}
.clear { clear: both; }
</style>
<script>
$(window).load(function() {
    var spotlight = {
        opacity: 0.2,
        imgWidth: $('.spotlightWrapper ul li').find('img').width(),
        imgHeight: $('.spotlightWrapper ul li').find('img').height()
    };
    
    $('.spotlightWrapper ul li').css({ 
        width: spotlight.imgWidth, 
        height: spotlight.imgHeight 
    });
    
    $('.spotlightWrapper ul li').hover(
        function() {
            $(this).find('img').addClass('active').css({ opacity: 1 });
            $(this).siblings('li').find('img').css({ opacity: spotlight.opacity });
        },
        function() {
            $(this).find('img').removeClass('active');
        }
    );
    
    $('.spotlightWrapper ul').bind('mouseleave', function() {
        $(this).find('img').css('opacity', 1);
    });
});
</script>
</head><body>
<h3>jQuery 背景牆聚光燈效果</h3>
<div class='spotlightWrapper'>
    <ul>
        <li><a href='#'><img src='images/1.jpg' /></a></li>
        <li><a href='#'><img src='images/2.jpg' /></a></li>
        <!-- 更多圖片 -->
    </ul>
    <div class='clear'></div>
</div>
</body></html>

核心邏輯解析

  1. 初始化:讀取首張圖片尺寸,統一 li 大小,避免佈局抖動
  2. 懸停進入:目標圖 opacity:1 + active 類(白邊 + z-index 置頂),兄弟圖 opacity:0.2
  3. 懸停離開:移除目標圖 active 類
  4. 離開容器:所有圖恢復 opacity:1

純 CSS 也可實現(:hover + ~ 兄弟選擇器),JS 版本兼容性更好且便於擴展動畫效果。

copyright © 萬盛學電腦網 all rights reserved