我是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%;
}
}
答案 0 :(得分:1)
我认为1个问题是srcImg是一个html元素的数组,而不是单个元素,所以当你写srcImg.onclick时它不起作用,因为你只能使用onclick来表示代表DOM的对象一个HTML元素。
答案 1 :(得分:0)
function imgClick(){
var target = event.target;
if(target.tagName !== "IMG"){ return }
target.src
modal.style.display = "block";
modalImg.src = target.src;
modalImg.alt = target.alt;
captionText.innerHTML = target.alt;
}
<div onclick="imgClick()">
<img src="./11.png" alt="111" >
</div>
srcImg是一个数组,onclick应该像这个元素一样使用.onclick = function(){...}