【发布时间】:2019-08-21 16:51:27
【问题描述】:
我需要创建一个图像灯箱。我基本上是从w3school的这个例子开始的,https://www.w3schools.com/howto/howto_js_lightbox.asp
但是,它不适用于纵向图像。例如。横向图像是 1200x800,纵向可以是 800x1200。
我需要图像以响应式调整大小并适用于水平和垂直图像。 它需要适用于所有现代浏览器、ios、android 以及 IE11。
你会看到我添加了“max-width: 1200px;”到 lightbox-content,它可以处理水平图像...但是由于垂直图像是 800 宽,它会放大并且高度超过。
<div class="lightbox">
<span class="close" onclick="closeLightbox()">×</span>
<div class="lightboxTitle">My Title</div>
<div class="lightbox-content">
<div class="slide"><img src="img1.jpg"></div>
<div class="slide"><img src="img2.jpg"></div>
<div class="slide"><img src="img2.jpg"></div>
<!-- Next/previous controls -->
<a class="prev" onclick="plusSlides(-1)">❮</a>
<a class="next" onclick="plusSlides(1)">❯</a>
</div>
</div>
/* The Modal (background) */
.lightbox {
display: none;
position: fixed;
z-index: 99999999;
padding-top: 60px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
}
/* Modal Content */
.lightbox-content {
position: relative;
margin: auto;
padding: 0;
width: 100%;
max-width: 1200px;
}
.lightboxTitle {
position: absolute;
top: 20px;
left: 25px;
font-size: 20px;
}
/* The Close Button */
.close {
color: white;
position: absolute;
top: 10px;
right: 25px;
font-size: 35px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: #FF8511;
text-decoration: none;
cursor: pointer;
}
/* Hide the slides by default */
.slide {
display: none;
}
.slide img {
width: 100%;
}
/* Next & previous buttons */
.prev,
.next {
cursor: pointer;
position: absolute;
top: 50%;
width: auto;
padding: 16px;
margin-top: -50px;
color: white;
font-weight: bold;
font-size: 20px;
transition: 0.6s ease;
border-radius: 0 3px 3px 0;
user-select: none;
-webkit-user-select: none;
}
/* Position the "next button" to the right */
.next {
right: 0;
border-radius: 3px 0 0 3px;
}
.prev {
left: 0;
border-radius: 3px 0 0 3px;
}
/* On hover, add a black background color with a little bit see-through */
.prev:hover,
.next:hover {
background-color: rgba(0, 0, 0, 0.8);
color: #FF8511;
}
【问题讨论】:
-
同时使用 max-width 和 max-height 属性。这将确保无论宽高比如何,都包含图像。
-
这不起作用,并且不会使图像对小屏幕做出响应。在这种情况下,图像仍然超出了灯箱内容的范围
-
我在这种情况下使用 vh 和 vw。我将最大高度设置为 80vh,最大宽度设置为 80vw,并在图像的两侧保持 10vh 和 10vw 的间隙。与更改屏幕尺寸无关,因为 vh 和 vw 会处理它。