我正在尝试利用以下模态示例https://codepen.io/centem/pen/wrYeMV但是我没有使用按钮来启动模态,而是在单击div矩形并在启动模式之前捕获其id时尝试启动模式。这是带有矩形的笔。 https://codepen.io/centem/pen/GQVGmw
这是我试图借用的示例中的模态javascript:
// Get the modal
var modal = document.getElementById('myModal');
// Get the button that opens the modal
var btn = document.getElementById("myBtn");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
答案 0 :(得分:0)
你不需要javascript。假设你正在使用Bootstrap 3。
<div class="span4 proj-div" data-toggle="modal" data-
target="#GSCCModal">Clickable content, graphics, whatever</div>
<div id="GSCCModal" class="modal fade" tabindex="-1" role="dialog"
aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-
hidden="true">× </button>
<h4 class="modal-title" id="myModalLabel">Modal title</h4>
</div>
<div class="modal-body">
...
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default"
data-dismiss="modal">Close</button>
<button type="button" class="btn btn-primary">Save changes</button>
</div>
</div>
</div>
答案 1 :(得分:0)
将class设置为所有div
<div class="foo"></div>
使用document.getElementsByClassName("foo");
代替document.getElementById("myBtn")
因为,您无法为多个元素设置相同的ID。但是你可以将同一个类设置为多个元素。
答案 2 :(得分:0)
您可以为每个矩形添加一个类,并为每个矩形添加一个click事件监听器。
var squares = document.getElementsByClassName("square");
for(var i = 0; i < squares.length; i++) {
squares[i].addEventListener('click', function(){
console.log(this.id);
modal.style.display = "block";
}, false);
}
答案 3 :(得分:0)
这是你修改过的js代码: //获取模态 var modal = document.getElementById(&#39; myModal&#39;);
// Get the button that opens the modal
var btn = document.getElementById("content");
// Get the <span> element that closes the modal
var span = document.getElementsByClassName("close")[0];
// When the user clicks the button, open the modal
btn.onclick = function() {
modal.style.display = "block";
//alert($(this).attr('class'))
$(".modal-content").find('p').append("This is the class: "+$(this).attr('class'))
}
// When the user clicks on <span> (x), close the modal
span.onclick = function() {
modal.style.display = "none";
}
// When the user clicks anywhere outside of the modal, close it
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}