如何创建:标签页式图片库

学习如何使用 CSS 和 JavaScript 创建标签页式图片库。

标签页式图片库

点击图像可展开:

Wuhan
Babisho
Shenzhen
Hangzhou
×

亲自试一试

创建标签页画廊

第一步 - 添加 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>

Use images to expand a specific image. After clicking the image in the column, the image will be displayed in the container below the column.

Second step - Add CSS:

Create four columns and set image styles:

/* Grid: four equal columns side by side */
.column {
  float: left;
  width: 25%;
  padding: 10px;
}
/* Set the style of the images inside the grid */
.column img {
  opacity: 0.8;
  cursor: pointer;
}
.column img:hover {
  opacity: 1;
}
/* Clear float after the column */
.row:after {
  content: "";
  display: table;
  clear: both;
}
/* Container of the expanded image (needs positioning to place the close button and text) */
.container {
  position: relative;
  display: none;
}
/* Text of the expanded image */
#imgtext {
  position: absolute;
  bottom: 15px;
  left: 15px;
  color: white;
  font-size: 20px;
}
/* Closeable button inside the image */
.closebtn {
  position: absolute;
  top: 10px;
  right: 15px;
  color: white;
  font-size: 35px;
  cursor: pointer;
}

Third step - Add JavaScript:

function myFunction(imgs) {
  // Get the expanded image
  var expandImg = document.getElementById("expandedImg");
  // Get image text
  var imgText = document.getElementById("imgtext");
  // Use the same src as the image clicked from the grid in the expanded image
  expandImg.src = imgs.src;
  // Use the value of the alt attribute of the clickable image as the text inside the expanded image
  imgText.innerHTML = imgs.alt;
  // Show container element (hidden with CSS)
  expandImg.parentElement.style.display = "block";
}

亲自试一试