圖片輪播不一定要靠 JS。善用 position: absolute 加上片段識別符(#a、#b、#c)的跳轉,就能讓瀏覽器自己完成「翻頁」。
完整程式碼如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="https://www.w3.org/1999/xhtml" xml:lang="zh" lang="zh">
<head profile="https://www.w3.org/2000/08/w3c-synd/#">
<meta http-equiv="content-language" content="zh-cn" />
<meta http-equiv="content-type" content="text/html;charset=gb2312" />
<style>
dl {
position: absolute;
width: 389px;
height: 154px;
border: 10px solid #eee;
}
dd {
margin: 0;
width: 389px;
height: 154px;
overflow: hidden;
}
img {
border: 1px solid black;
}
dt {
position: absolute;
right: 3px;
top: 50px;
}
a {
display: block;
margin: 1px;
width: 20px;
height: 20px;
text-align: center;
font: 700 12px/20px "宋體", sans-serif;
color: #fff;
text-decoration: none;
background: #666;
border: 1px solid #fff;
filter: alpha(opacity=40);
opacity: .4;
}
a:hover {
background: #000;
}
</style>
</head>
<body>
<dl>
<dt><a href="#a" title="">1</a><a href="#b" title="">2</a><a href="#c" title="">3</a></dt>
<dd>
<img src="/uploadfile/200806/17/86181645617.jpg" alt="" title="" id="a" />
<img src="/uploadfile/200806/17/61181646102.jpg" alt="" title="" id="b" />
<img src="/uploadfile/200806/17/D9181646550.jpg" alt="" title="" id="c" />
</dd>
</dl>
</body>
</html>
整個舞台是 <dl>,寬高寫死並加上淺色外框;<dd> 是取景窗,靠 overflow: hidden 只露出第一格可見範圍。三張圖片各自帶上 id="a"、id="b"、id="c",而 <dt> 內的三個連結分別指向這些錨點。
點擊連結時,瀏覽器會把帶錨點的元素捲到視窗內,於是原本被裁掉的圖片就被「翻」進取景框。 numbering 按鈕用半透明(opacity: .4)呈現,hover 時加深底色,回饋明確。
這種做法的優點是零依賴、載入輕;缺點也很清楚:無法自動播放、也沒有淡入淡出等過場動畫。若只需要簡約的手動切換,它依然是相當優雅的方案。