圖片牆初始半透明,鼠標懸停某圖片時該圖變不透明並加白邊突出,其他圖保持半透明;鼠標離開牆區域所有圖恢復全顯示。
<!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>
li 大小,避免佈局抖動opacity:1 + active 類(白邊 + z-index 置頂),兄弟圖 opacity:0.2active 類opacity:1純 CSS 也可實現(:hover + ~ 兄弟選擇器),JS 版本兼容性更好且便於擴展動畫效果。