焦點圖輪播是首頁最常見的元件之一。本文示範一款淡入淡出風格的幻燈片:圖片以透明度漸變的方式切換,並搭配右下角的數字按鈕可手動切換,滑鼠移入時暫停自動播放、移開後恢復。完整程式碼如下:
復制代碼 代碼如下:<!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>JS+CSS淡入式焦點圖片幻燈切換效果</title>
<style>
body,div,ul,li{margin:0;padding:0;}
ul{list-style-type:none;}
body{background:#000; text-align:center; font:12px/20px Arial;}
#box{position:relative; width:322px; height:172px; background:#fff; border-radius:5px; border:8px solid #fff; margin:10px auto;}
#box .list{position:relative; width:320px; height:240px; overflow:hidden; border:1px solid #ccc;}
#box .list li{position:absolute; top:0; left:0; width:320px; height:240px; opacity:0; filter:alpha(opacity=0);}
#box .list li.current{opacity:1; filter:alpha(opacity=100);}
#box .count{position:absolute; right:0; bottom:5px;}
#box .count li{color:#fff; float:left; width:20px; height:20px; cursor:pointer; margin-right:5px; overflow:hidden; background:#F90; opacity:0.7; filter:alpha(opacity=70); border-radius:20px;}
#box .count li.current{opacity:1; filter:alpha(opacity=100); font-weight:700; background:#f60;}
</style>
<script type="text/javascript">
window.onload = function () {
var oBox = document.getElementById("box");
var aUl = document.getElementsByTagName("ul");
var aImg = aUl[0].getElementsByTagName("li");
var aNum = aUl[1].getElementsByTagName("li");
var timer = play = null;
var i = index = 0;
for (i = 0; i < aNum.length; i++){ aNum[i].index = i; aNum[i].onmouseover = function(){ show(this.index) } }
oBox.onmouseover = function(){ clearInterval(play) };
oBox.onmouseout = function(){ autoPlay() };
function autoPlay(){
play = setInterval(function(){ index++; index >= aImg.length && (index = 0); show(index); }, 2000);
}
autoPlay();
function show(a){
index = a; var alpha = 0;
for (i = 0; i < aNum.length; i++) aNum[i].className = "";
aNum[index].className = "current";
clearInterval(timer);
for (i = 0; i < aImg.length; i++){ aImg[i].style.opacity = 0; aImg[i].style.filter = "alpha(opacity=0)"; }
timer = setInterval(function(){
alpha += 2; alpha > 100 && (alpha = 100);
aImg[index].style.opacity = alpha / 100;
aImg[index].style.filter = "alpha(opacity = " + alpha + ")";
alpha == 100 && clearInterval(timer);
}, 20);
}
};
</script>
</head>
<body>
<div id="box">
<ul class="list">
<li class="current"><img src="/images/m01.jpg" width="320" height="240" /></li>
<li><img src="/images/m02.jpg" width="320" height="240" /></li>
<li><img src="/images/m03.jpg" width="320" height="240" /></li>
</ul>
<ul class="count">
<li class="current">1</li><li>2</li><li>3</li>
</ul>
</div>
</body>
</html>
核心在 show 函式:先用 setInterval 每 20 毫秒遞增 alpha,做出淡入動畫;autoPlay 每 2 秒切換下一張;滑鼠移入時清除計時器暫停,移開再啟動。兼顧自動輪播與手動切換,是相當實用的首頁元件。