gpt4 book ai didi

Javascript:避免多个弹出框/检查div是否为空

转载 作者:行者123 更新时间:2023-11-28 02:37:10 27 4
gpt4 key购买 nike

我创建了一个弹出框,当用户单击按钮时会出现该框。目前我能够让盒子出现但是当用户关闭它并重新打开它时代码再次运行并且另一个盒子堆叠在旧盒子的顶部。

我想做的是无论用户点击框多少次它只显示一个框...我的想法可能是检查它是否为空类似于 How do I check if an HTML element is empty using jQuery?然而,到目前为止还没有奏效。

对菜鸟白痴有什么建议吗?提前感谢所有回复。

<button onclick="popup()">text</button>

<script>
var box = document.getElementById('popupbox');

function popup(){
box.style.display = "block";
var content = document.createElement('div');
content.className = 'boxstyle';
content.innerHTML = ' ...a handful of tags...';
box.appendChild(content);}

function exit(){
box.style.display = "none";}
</script>

最佳答案

您可以使用模态框创建弹出窗口,如下所示。我刚刚复制了代码 from here

<!DOCTYPE html>
<html>
<head>
<style>
/* The Modal (background) */
.modal {
display: none; /* Hidden by default */
position: fixed; /* Stay in place */
z-index: 1; /* Sit on top */
padding-top: 100px; /* Location of the box */
left: 0;
top: 0;
width: 100%; /* Full width */
height: 100%; /* Full height */
overflow: auto; /* Enable scroll if needed */
background-color: rgb(0,0,0); /* Fallback color */
background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
}

/* Modal Content */
.modal-content {
background-color: #fefefe;
margin: auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}

/* The Close Button */
.close {
color: #aaaaaa;
float: right;
font-size: 28px;
font-weight: bold;
}

.close:hover,
.close:focus {
color: #000;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>

<h2>Modal Example</h2>

<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- The Modal -->
<div id="myModal" class="modal">

<!-- Modal content -->
<div class="modal-content">
<span class="close">&times;</span>
<p>Some text in the Modal..</p>
</div>

</div>

<script>
// 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";
}
}
</script>

</body>
</html>

关于Javascript:避免多个弹出框/检查div是否为空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47362911/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com