javascript - 如何使用而不是触发模态
问题描述
单击按钮时,我使用此(w3school)代码触发模式
// 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 on 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";
}
}
而不是使用按钮,我想使用<a>
'sonclick=function()
方法来触发模态。我已经尝试交换*tn.onlclick
-part,但这没有用。如何做到这一点?
解决方案
您可以将a
标签与preventDefault
const opener = document.querySelector('.btn');
opener.onclick = function(e) {
e.preventDefault(); // to prevent link's default behaviour
modal.style.display = "block";
}
<a class="btn" href="#">Open</a>
推荐阅读
- php - 当我调用它来登录时,我的 AJAX 和 PHP 有什么问题?
- arrays - 推送一个数组同时foreach其他数组laravel
- testing - 测试咖啡馆 - 页面对象 - 消费模块
- reactjs - 使用 Redux 和 React Router 在 React 应用程序的浏览器中重新加载 url 导致存储状态未定义
- javascript - 滚动上的多个变形
- javascript - Rails 5.2+:为什么仍然使用带有 webpacker 的资产管道?
- python - 我需要做什么才能将 python 可执行文件添加到 HTML?
- jenkins - 我可以在 Jenkins 中使用 Scripted Pipeline 指定节点吗?
- html - 使用 flexbox 在标题中定位 h1、h2 和 2 个图像
- python - 寻找检索电子邮件并将其显示在 HTML 收件箱页面中的方法