简体   繁体   English

div内span标签的onclick事件

[英]onclick event for span tag inside div

I'm trying to make a button that opens a image on my webpage and then when you press the x in the corner it closes.我正在尝试制作一个按钮,在我的网页上打开一个图像,然后当你按下角落里的 x 时它会关闭。 I got the image to open, but the close button isn't working and I don't know why.我打开图像,但关闭按钮不起作用,我不知道为什么。

 var modal = document.getElementById("myModal"); var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); img.onclick = function() { modal.style.display = "block"; modalImg.src = "image link"; } function close(i) { document.getElementById(i).style.display = "none"; }
 <div class="sidebar"> <div class="schedule"> <button id="myImg"> <h4><span class="fa fa-caret-right"></span> Schedule</h4> <div id="myModal" class="modal"> <span class="close" style="z-index: 999;" onclick="close('myModal')">&times;</span> <img class="modal-content" id="img01" /> </div> </button> </div> </div>

You have a button inside a modal which is inside a button.您在一个按钮内的模态中有一个按钮。 That is a problem since the outer button prevents the inner button from working.这是一个问题,因为外部按钮会阻止内部按钮工作。 Lets break those out a bit, and use a relative reference to close the modal.让我们稍微打破一下,并使用相对引用来关闭模式。

First separate the modal from the button.首先将模态与按钮分开。

 var modal = document.getElementById("myModal"); var img = document.getElementById("myImg"); var modalImg = document.getElementById("img01"); img.onclick = function() { modal.style.display = "block"; modalImg.src = "https://picsum.photos/200/300"; } function closeModal(el) { el.closest('.modal').style.display = "none"; }
 #myModal { display: none; } .close { display: inline-block; padding: 5px; cursor: pointer; }
 <div id="myModal" class="modal"> <span class="close" style="z-index: 999;" onclick="closeModal(this)">&times;</span> <img class="modal-content" id="img01" /> </div> <div class="sidebar"> <div class="schedule"> <button id="myImg"> <h4><span class="fa fa-caret-right"></span> Schedule</h4></button> </div> </div>

Using relative references like that are handy when you have more than one element that can call them.当您有多个可以调用它们的元素时,使用这样的相对引用会很方便。 Additionally it frees you from having to call an ID.此外,它使您无需拨打 ID。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM