如何操作 - 模态图像
了解如何使用 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";
}
自己动手试一试 »