拆解當當網品牌館首頁輪播效果:綠色半透明標題區疊加於圖片上方,滑鼠移至標籤切換對應圖片,三張大圖自動輪播淡入淡出。
<div id="carousel">
<div id="carouselimg" class="content_top">
<div id="imgcontainer" class="slide_panel">
<a href="..."><img src="images/band_lx_717x280.gif" /></a>
<a href="..."><img src="images/band_agz_717x280.gif" /></a>
<a href="..."><img src="images/band_qb_717x280.gif" /></a>
</div>
</div>
<div id="carouseltitle">
<ul>
<li><a href="#">聯想 <span>lenovo</span></a></li>
<li><a href="#">愛國者 <span>aigo</span></a></li>
<li><a href="#">倩碧 <span>CLINIQUE</span></a></li>
</ul>
</div>
</div>
#carousel { position: relative; border: 1px solid #DFDFDF; border-top: none; }
#carouselimg { position: relative; overflow: hidden; height: 280px; }
#imgcontainer { position: absolute; left: 0; top: 0; width: 2151px; } /* 3張圖寬度總和 */
#imgcontainer img { float: left; border: 0; }
#carouseltitle { position: absolute; bottom: 0; z-index: 10; }
#carouseltitle li {
float: left; width: 239px; height: 30px; line-height: 30px;
text-align: center; font-size: 14px; background: #000; color: #FFF;
cursor: pointer; opacity: .6; filter: alpha(opacity=60);
}
#carouseltitle li.active { background: #cfaf73; opacity: .9; filter: alpha(opacity=90); }
#carouseltitle li.active a { color: #000; }
#carouseltitle a { text-decoration: none; color: #fff; }
#carouseltitle a span { font-family: Arial; }
(function($) {
$.fn.carousel = function(options) {
var opts = $.extend({ interval: 3000, fadeSpeed: 500 }, options);
return this.each(function() {
var $this = $(this);
var $imgs = $this.find('#imgcontainer img');
var $titles = $this.find('#carouseltitle li');
var index = 0, timer;
function show(idx) {
$imgs.stop(true, true).fadeOut(opts.fadeSpeed).eq(idx).fadeIn(opts.fadeSpeed);
$titles.removeClass('active').eq(idx).addClass('active');
}
function auto() {
timer = setInterval(function() {
index = (index + 1) % $imgs.length;
show(index);
}, opts.interval);
}
$titles.hover(function() {
clearInterval(timer);
index = $titles.index(this);
show(index);
}, function() { auto(); });
auto(); // 啟動
});
};
})(jQuery);
// 初始化
$('#carousel').carousel({ interval: 4000, fadeSpeed: 600 });
#imgcontainer 寬度 = 單圖寬度 × 圖片數,float:left 排列position:absolute; bottom:0; z-index:10 置於圖片上方opacity + IE filter:alpha 相容.stop(true,true) 清除佇列並跳至終狀態,避免快速滑鼠移動造成動畫堆疊hover 進入清除定時器,離開重啟
transition: opacity 0.5s 替代 jQuery fadeIn/Out,效能更佳IntersectionObserver 實現進入視口才啟動輪播aria-label、鍵盤焦點控制、prefers-reduced-motion 媒體查詢停用動畫