首页 > 解决方案 > 如何使用而不是触发模态

问题描述

单击按钮时,我使用此(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,但这没有用。如何做到这一点?

标签: javascripthtmlcss

解决方案


您可以将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>


推荐阅读