如何操作 - 模態影像
瞭解如何使用 CSS 和 JavaScript 建立響應式模態影像。
模態框影像
模態框是顯示在當前頁面之上的對話方塊/彈出視窗。
此示例使用了上一個示例的大部分程式碼,即 模態框,在這個示例中,我們使用影像。

×
步驟 1) 新增 HTML
示例
<!-- 觸發模態框 -->
<img id="myImg" src="img_snow.jpg" alt="Snow" style="width:100%;max-width:300px">
<!-- 模態框 -->
<div id="myModal" class="modal">
<!-- 關閉按鈕 -->
<span class="close">×</span>
<!-- 模態內容 (影像) -->
<img class="modal-content" id="img01">
<!-- 模態標題 (影像文字) -->
<div id="caption"></div>
</div>
步驟 2) 新增 CSS
示例
/* 樣式用於觸發模態框的影像 */
#myImg {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
#myImg:hover {opacity: 0.7;}
/* 模態框(背景) */
.modal {
display: none; /* 預設隱藏 */
position: fixed; /* 定位 */
z-index: 1; /* 位於頂部 */
padding-top: 100px; /* 框的位置 */
left: 0;
top: 0;
width: 100%; /* 全寬度 */
height: 100%; /* 全高度 */
overflow: auto; /* 如有需要,啟用滾動 */
background-color: rgb(0,0,0); /* 備用顏色 */
background-color: rgba(0,0,0,0.9); /* 黑色帶透明度 */
}
/* 模態內容 (影像) */
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
}
/* 模態影像的標題 (影像文字) - 與影像同寬 */
#caption {
margin: auto;
display: block;
width: 80%;
max-width: 700px;
text-align: center;
color: #ccc;
padding: 10px 0;
height: 150px;
}
/* 新增動畫 - 模態框縮放 */
.modal-content, #caption {
animation-name: zoom;
animation-duration: 0.6s;
}
@keyframes zoom {
from {transform:scale(0)}
to {transform:scale(1)}
}
/* 關閉按鈕 */
.close {
position: absolute;
top: 15px;
right: 35px;
color: #f1f1f1;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
color: #bbb;
text-decoration: none;
cursor: pointer;
}
/* 在較小螢幕上影像寬度為 100% */
@media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
}
步驟 3) 新增 JavaScript
示例
// 獲取模態框
var modal = document.getElementById("myModal");
// 獲取影像並將其插入模態框中 - 使用其“alt”文字作為標題
var img = document.getElementById("myImg");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// 獲取關閉模態框的 <span> 元素
var span = document.getElementsByClassName("close")[0];
// 當用戶點選 <span> (x) 時,關閉模態框
span.onclick = function() {
modal.style.display = "none";
}
自己動手試一試 »