javascript - 如何为模态对话框设置计时器以在按下按钮时出现
问题描述
嗨,我有一个 onclick 按钮。当我按下这个 onclick 按钮时,一个模态对话框应该会在 5 秒(5000 毫秒)后出现。然而,在 5 秒后,模态关闭并在 5 后重新打开,就好像它被循环了一样。代码看起来一切都很好,但我不知道我哪里出错了。
我想要的是:
1) 按下 onclick 时,模态对话框会在 5 秒后打开。除非有人按下保存按钮,否则模式不应关闭。2)当按下“保存”按钮时,模态对话框关闭并重置。3) 模态对话不会再次重新打开。它仅在单击按钮后 5 秒打开。
我希望这很清楚。
任何帮助将不胜感激
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");
function toggleModal() {
setTimeout(toggleModal, 5000)
modal.classList.toggle("show-modal");
}
trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
.modal {
position: fixed;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
opacity: 0;
visibility: hidden;
transform: scale(1.1);
transition: visibility 0s linear 0.25s, opacity 0.25s 0s, transform 0.25s;
}
.modal-content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
background-color: white;
padding: 1rem 1.5rem;
width: 24rem;
border-radius: 0.5rem;
}
.close-button {
float: right;
width: 1.5rem;
line-height: 1.5rem;
text-align: center;
cursor: pointer;
border-radius: 0.25rem;
background-color: lightgray;
}
.close-button:hover {
background-color: darkgray;
}
.show-modal {
opacity: 1;
visibility: visible;
transform: scale(1.0);
transition: visibility 0s linear 0s, opacity 0.25s 0s, transform 0.25s;
}
<button class="trigger">Click here </button>
<div class="modal">
<div class="modal-content">
<h1>
<label><b>Please state your confidence with this decision (0-100%)</b></label>
<p>
<input class="bottomaftertrialquestions" type="number" placeholder="Type here" name="conf1d3nce"min="0" max="100" required>
</p>
<p></h1>
<button type="button" class="close-button">SAVE</button>
</div>
</div>
. 我不确定我的代码有什么问题才能让它工作
解决方案
你应该试试这个
<!DOCTYPE html>
<html>
<body>
<p>Click "Try it". Wait 3 seconds, and the page will alert "Hello".</p>
<button onclick="setTimeout(myFunction, 3000);">Try it</button>
<script>
function myFunction() {
alert('Hello');
}
</script>
</body>
</html>
推荐阅读
- mysql - 我如何同时插入具有所有不同子查询值的同一行,几乎就像对子查询的迭代?
- python - 在列表字典中查找键的索引
- javascript - 检查光标是否是输入文本的结尾
- python - Django:模型类 __main__.Source 在 PyCharm 中加载模型时未声明显式 app_label
- ansible - Ansible如何将控制器主机连接到在同一个虚拟机中运行的另一台主机?
- c - 分配器工作良好,除了数字 1,2 和 3
- django - 姜戈。在models.py中的哪里放置自定义方法?
- scala - 不同的咖喱方法
- google-cloud-firestore - 通过 json 预加载 Cloud Firestore?
- reactjs - Material UI + Jest + Enzyme 测试标签