我希望能够在单击链接时显示和隐藏某个 div,但我的代码只有在使用按钮时才有效。为什么会发生这种情况,我该如何解决?
这是我的代码:
.popup {
position: relative;
display: inline-block;
}
.popup-content {
display: none;
position: absolute;
width: 1000px;
}
.show {
display:block;
}
<div class="popup">
<button onclick="showPopup()" class="btnPopup thePopup">POPUP FROM BUTTON</button>
<a class="linkStyle thePopup" onclick="javascript:showPopup()" href="#" return false;>POPUP FROM LINK</a>
<div id="myPopup" class="popup-content" style="border:1px; border-style:solid; margin:10px; padding: 10px;width:200px;">
Lorem ipsum dolor sit amet, consectetur adipisicing elit. Voluptatibus quasi voluptas impedit. Culpa impedit?
</div>
</div>
<script>
/* When the user clicks on the button,
toggle between hiding and showing the dropdown content */
function showPopup() {
event.preventDefault();
document.getElementById("myPopup").classList.toggle("show");
return false;
}
// Close the dropdown if the user clicks outside of it
window.onclick = function(event) {
if (!event.target.matches('.thePopup')) {
var dropdowns = document.getElementsByClassName("popup-content");
var i;
for (i = 0; i < dropdowns.length; i++) {
var openDropdown = dropdowns[i];
if (openDropdown.classList.contains('show')) {
openDropdown.classList.remove('show');
}
}
}
}
</script>
这里还有一个codepen的链接: http://codepen.io/ZlatinaNyagolova/pen/LkOgzk
更新:
我向按钮和链接添加了另一个类,并在关闭函数的监听器中使用了该类。这修好了! :)
最佳答案
弹出窗口打开正常,但您关闭弹出窗口的功能导致了问题。
您将监听器附加到整个窗口的“onclick”函数,然后继续关闭弹出窗口 - 除非事件目标匹配“.btnPopup”,即您的按钮被点击。
所以发生的事情是:
- 您单击按钮,它的“onclick”函数显示弹出窗口,窗口的“onclick”函数运行,但不执行任何操作,因为事件目标匹配“.btnPopup”
- 您单击链接,其“onclick”函数显示弹出窗口,窗口的“onclick”函数运行,并且由于事件目标与 .btnPopup 不匹配,它立即关闭弹出窗口。
您可以轻松修复它,例如向按钮和链接添加另一个类,并在您的 window.onclick 监听器中使用该类来检查是否单击“某物”以打开弹出窗口:
<button onclick="showPopup()" class="btnPopup Popup">POPUP FROM BUTTON</button>
<a class="linkStyle Popup" onclick="showPopup()" href="#">POPUP FROM LINK</a>
...
window.onclick = function(event) {
if (!event.target.matches('.Popup')) {
//Proceed with closing the popup
关于javascript - 切换隐藏/显示 div 适用于按钮,但不适用于链接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38367011/