我在做网页大作业过程中,从https://www.runoob.com/w3cnote/javascript-image-modal.html摘抄到图片弹窗的代码。
其中的JS代码为下
// 获取弹窗
var modal = document.getElementById('myModal');
// 获取图片插入到弹窗 - 使用 "alt" 属性作为文本部分的内容
var img1 = document.getElementById('img1');
var modalImg = document.getElementById("img01");
var captionText = document.getElementById("caption");
img1.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
// 获取 <span> 元素,设置关闭按钮
var span = document.getElementsByClassName("close")[0];
// 当点击 (x), 关闭弹窗
span.onclick = function() {
modal.style.display = "none";
}
因为图片较多,我给图片添加了不同的id,不断重复了代码,也修改相应的名称
var img1 = document.getElementById('img1');
以及代码
img1.onclick = function(){
modal.style.display = "block";
modalImg.src = this.src;
captionText.innerHTML = this.alt;
}
但最后运行只有前6张图片可以实现图片弹窗,请问我该如何修改?
你可以试着把,图片的地址写成一个json格式或者数组,推荐json,{[imgname:"1",imgsrc:""]....},这样循环遍历创建,img标签。要不然你把效果图发出来看看