javascript - 在页面加载时打开 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";
}
}
解决方案
当您获得模式时 - 只需将样式设置为显示:块
var modal = document.getElementById('myModal');
modal.style.display = "block"
或者更好 - 拥有具有样式的类,然后添加或删除类以显示/隐藏模式。您可以将 display: none 设置为默认值,然后设置一个 allwos display: 在添加时阻止的“活动”类。
显示模态
modal.classList.add('active')
隐藏模态
modal.classList.remove('active')
// css
#myModal{
display: none;
}
#myModal.active {
display: block;
}
推荐阅读
- .net - 在 .Net Core 3.1 中使用 MongoDB API 在 Azure Cosmos DB 中出现重复密钥问题
- javascript - React onClick 组件执行函数
- python - 写入空 csv 文件时出现权限被拒绝错误
- amazon-web-services - 使用 AWS CDK 将 Lambda 触发器添加到导入的 Cognito 用户池
- mongodb - 如何使用 Mongodb 从 JSON 字段中提取值?
- c++ - C++ 继承私有成员
- c# - 创建托管服务时,框架会自动注入哪些资源?
- flutter - 在 MaterialApp 之上使用 MultiProvider 定义的服务中访问本地化
- c# - 卡夫卡消费者没有收到消息
- javascript - Web Audio Api - start() 函数无法识别