操作方法 - 選項卡畫廊
學習如何使用 CSS 和 JavaScript 建立帶選項卡的圖片庫。
選項卡畫廊
點選圖片進行放大

自然
建立選項卡畫廊
步驟 1) 新增 HTML
示例
<!-- 網格:四列 -->
<div class="row">
<div class="column">
<img src="img_nature.jpg" alt="Nature" onclick="myFunction(this);">
</div>
<div class="column">
<img src="img_snow.jpg" alt="Snow" onclick="myFunction(this);">
</div>
<div class="column">
<img src="img_mountains.jpg" alt="Mountains" onclick="myFunction(this);">
</div>
<div class="column">
<img src="img_lights.jpg" alt="Lights" onclick="myFunction(this);">
</div>
</div>
<!-- 展開的圖片容器 -->
<div class="container">
<!-- 關閉圖片 -->
<span onclick="this.parentElement.style.display='none'" class="closebtn">×</span>
<!-- 展開的圖片 -->
<img id="expandedImg" style="width:100%">
<!-- 圖片文字 -->
<div id="imgtext"></div>
</div>
使用圖片展開特定圖片。在網格中點選的圖片會顯示在網格下方的容器中。
步驟 2) 新增 CSS
建立四列並樣式化圖片
示例
/* 網格:四等分並排浮動的列 */
.column {
float: left;
width: 25%;
padding: 10px;
}
/* 網格內圖片的樣式 */
.column img {
opacity: 0.8;
cursor: pointer;
}
.column img:hover {
opacity: 1;
}
/* 清除列後的浮動 */
.row:after {
content: "";
display: table;
clear: both;
}
/* 展開的圖片容器(需要定位來定位關閉按鈕和文字) */
.container {
position: relative;
display: none;
}
/* 展開的圖片文字 */
#imgtext {
position: absolute;
bottom: 15px;
left: 15px;
color: white;
font-size: 20px;
}
/* 圖片內的可關閉按鈕 */
.closebtn {
position: absolute;
top: 10px;
right: 15px;
color: white;
font-size: 35px;
cursor: pointer;
}
步驟 3) 新增 JavaScript
示例
function myFunction(imgs) {
// 獲取展開的圖片
var expandImg = document.getElementById("expandedImg");
// 獲取圖片文字
var imgText = document.getElementById("imgtext");
// 使用與網格中點選的圖片相同的 src 來展開圖片
expandImg.src = imgs.src;
// 使用可點選圖片的 alt 屬性值作為展開圖片中的文字
imgText.innerHTML = imgs.alt;
// 顯示容器元素(在 CSS 中隱藏)
expandImg.parentElement.style.display = "block";
}
自己動手試一試 »