如何創建:標簽頁式圖片庫
學習如何使用 CSS 和 JavaScript 創建標簽頁式圖片庫。
標簽頁式圖片庫
點擊圖像可展開:




×
創建標簽頁畫廊
第一步 - 添加 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>
使用圖像來展開特定的圖像。點擊列中的圖像后,將在列下方的容器中顯示該圖像。
第二步 - 添加 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; }
第三步 - 添加 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"; }