【发布时间】:2018-05-02 01:00:21
【问题描述】:
我完全是 javascript 新手,这可能非常简单。我正在尝试创建代码,当我单击图像时,相同的图像将以模式启动。这适用于查看完整尺寸图像的作品集。我的 javascript 控制台中没有错误,但是当我单击图像时没有任何反应。
javascript:
var modal = document.getElementById("myModal");
var srcImg = document.getElementsByClassName("showFull");
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
srcImg.onclick = function () {
modal.style.display = "block";
modalImg.src = this.src;
modalImg.alt = this.alt;
captionText.innerHTML = this.alt;
}
var exit = document.getElementsByClassName("close")[0];
exit.onclick = function () {
modal.style.display = "none";
};
html:
<div class="mySlides fade">
<img class="slide showFull" src="images/mikesHarder.jpg alt="caption 123" style="width:100%" />
</div>
<div class="mySlides fade">
<img class="slide showFull" src="images/Going-Green.jpg" alt="caption 123" style="width:100%" />
</div>
<div id="myModal" class="modal">
<!-- The Close Button -->
<span class="close">×</span>
<!-- Modal Content -->
<img id="img01" class="modal-content"/>
<div id="caption"></div>
</div>
css:
.showFull {
border-radius: 5px;
cursor: pointer;
transition: 0.3s;
}
.showFull:hover {opacity: 0.9;}
.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.8);
}
.modal-content {
margin: auto;
display: block;
width: 80%;
max-width: 480px;
}
.modal-content {
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;
}
@media only screen and (max-width: 700px){
.modal-content {
width: 100%;
}
}
【问题讨论】:
-
document.getElementsByClassName返回一个数组,循环遍历它并添加onclick像:srcImg.forEach(e => { e.onclick = function () { ... } } ); -
getElementsByClassName()返回一个节点列表 - 元素的集合。您需要循环/迭代集合。 另外您的图像img标记之一需要修复。src="images/mikesHarder.jpg alt="caption 123"src末尾缺少双引号,这将使其他属性无效。 -
修复了img标签问题,然后就可以正常工作了。
标签: javascript css simplemodal