2 回答
TA贡献1821条经验 获得超4个赞
听起来当光标悬停在图像上时,悬停状态本质上是分层的在可点击图像元素的顶部,因此阻止用户点击它并激活弹出模式。尝试将侦听器添加到悬停状态元素,或者将标题与图像分组,以便可以单击它们。我已将您的示例与下面的代码片段配对。
干杯!
var modalEle = document.querySelector(".modal");
var modalImage = document.querySelector(".modalImage");
Array.from(document.querySelectorAll(".overlay")).forEach(item => {
item.addEventListener("click", event => {
modalEle.style.display = "block";
modalImage.src = event.target.parentNode.querySelector(".ImgThumbnail").src;
});
});
document.querySelector(".close").addEventListener("click", () => {
modalEle.style.display = "none";
});
body {
color: #66704D;
letter-spacing: 3px;
}
/*overlay*/
.container {
position: relative;
width: 300px;
height: 200px;
}
.ImgThumbnail {
display: block;
width: 100%;
height: auto;
}
.overlay {
position: absolute;
top: 0;
bottom: 0;
left: 0;
right: 0;
height: 100%;
width: 100%;
opacity: 0;
transition: .5s ease;
background-color: rgba(255, 255, 255, 0.9);
}
.container:hover .overlay {
opacity: 1;
}
.text {
color: #66704d;
font-size: 20px;
letter-spacing: 5px;
position: absolute;
top: 50%;
left: 50%;
-webkit-transform: translate(-50%, -50%);
-ms-transform: translate(-50%, -50%);
transform: translate(-50%, -50%);
text-align: center;
}
/*modal*/
.ImgThumbnail {
cursor: pointer;
transition: 0.3s;
}
.modal {
display: none;
position: fixed;
z-index: 1;
padding-top: 100px;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(255, 255, 255, 0.85);
}
.modalImage {
margin: 0 auto;
display: block;
width: 80%;
height: auto;
max-width: 1024px;
}
.close {
position: absolute;
top: 15px;
right: 35px;
color: #66704d;
font-size: 40px;
font-weight: bold;
transition: 0.3s;
}
.close:hover,
.close:focus {
cursor: pointer;
}
@media only screen and (max-width: 700px) {
.modalImage {
width: 100%;
}
}
<div class="container">
<div class="imgGroup">
<img class="ImgThumbnail" src="https://placehold.it/300x200" alt="">
<div class="overlay">
<div class="text">caption content</div>
</div>
</div>
</div>
<div class="modal">
<span class="close">×</span>
<img class="modalImage" id="img01">
</div>
TA贡献1818条经验 获得超7个赞
查看演示:https://codepen.io/turibamwe/pen/xxwGozx
使用这个JavaScript:
<script>
var modalEle = document.querySelector(".modal");
var modalImage = document.querySelector(".modalImage");
Array.from(document.querySelectorAll(".ImgThumbnail + .overlay")).forEach(item => {
var itemImage = item.parentNode.firstElementChild.getAttribute("src");
item.addEventListener("click", event => {
modalEle.style.display = "block";
modalImage.src = itemImage//event.target.src;
});
});
document.querySelector(".close").addEventListener("click", () => {
modalEle.style.display = "none";
});
</script>
- 2 回答
- 0 关注
- 112 浏览
添加回答
举报