我的照片下方有“了解更多”按钮。我试图弄清楚如何用每个按钮显示不同的模态内容来编写js。
session.gc_maxlifetime : 60
session.gc_probability : 1
session.gc_divisor : 1
session.cookie_lifetime : 60
html看起来像:
var modal = document.getElementsByClassName("myModal");
var btn = document.getElementById("myBtn");
var span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
};
我有5个部分需要显示。每个附加部分看起来都像上面那样。我知道按钮需要一个唯一的ID,我认为设置课程是我遇到麻烦的地方。
答案 0 :(得分:0)
首先,您无法在页面中重复ID ...根据定义,它们是唯一的。
使用类和循环类集合来处理实例,例如:
// collection of galleries
var galleries = document.getElementsByClassName('gallery');
// iterate galleries collection
for (var i = 0; i < galleries.length; i++) {
let gal = galleries[i], // specific gallery instance
modal = gal.querySelector('.modal'), // modal within this gallery instance
learnBtn = gal.querySelector('.learn');//button within this gallery instance
let toggleModal = function(){
modal.classList.toggle('show');
};
learnBtn.onclick = modal.onclick = toggleModal;
}
.modal {
display: none;
}
.modal.show {
display: block;
background: #eaeaea;
position: absolute;
top: 0;
left: 0;
right: 0;
bottom: 0
}
.modal-content {
background: white;
border: 3px solid #ccc;
margin: 20%;
padding:30px;
}
<div class="gallery">
<h3>Gallery 1</h3>
<button class="learn">Learn More</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Gallery 1 modal
</p>
</div>
</div>
</div>
<div class="gallery">
<h3>Gallery 2</h3>
<button class="learn">Learn More</button>
<div class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>Gallery 2 modal
</p>
</div>
</div>
</div>