Как запустить модальное окно с <a>вместо <button> - PullRequest
0 голосов
/ 08 мая 2020

Я использую this (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> s onclick=function() метод для запуска модального окна. Я уже пытался заменить *tn.onlclick -часть, но это не помогло. Как выполнить sh это?

Ответы [ 2 ]

1 голос
/ 08 мая 2020

Вы можете использовать тег 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>
0 голосов
/ 08 мая 2020

Включите якорь в свой html и прикрепите обработчик событий, аналогичный тому, который используется для кнопки. Вы можете добавить код для подавления поведения по умолчанию при щелчке по привязке (ie. После uri в атрибуте href).

Если вы не используете атрибут onclick, но назначаете обработчики через dom api с addEventListener, утверждать, что элементы для присоединения обработчиков действительно существуют. Для этого предназначена функция ready, прикрепленная к событию окна load.

let a
  , btn
  , modal
  , span
  ;

// When the user clicks on the button, open the modal
function openModal(eve) {
  if (eve.target.tagName.toLowerCase() === 'a') {
    // Prevent standard link behavior
    eve.preventDefault();
  }
  modal.style.display = "block";
} // openModal

// When the user clicks on <span> (x), close the modal
function closeModal(eve) { 
  modal.style.display = "none";
} // closeModal

function ready () {
  modal = document.getElementById("myModal");

  // Get the anchor that opens the modal
  a = document.getElementById("myAnchor");

  // Get the button that opens the modal
  btn = document.getElementById("myBtn");

  // Get the <span> element that closes the modal
  span = document.getElementsByClassName("close")[0];

  a.addEventListener ( 'click', openModal );
  btn.addEventListener ( 'click', openModal );
  span.addEventListener ( 'click', closeModal );
} // ready


// When the user clicks anywhere outside of the modal, close it
window.onclick = function(eve) {
  if (eve.target === modal) {
    modal.style.display = "none";
  }
};
window.addEventListener ( 'load', ready );
/* The Modal (background) */
.modal {
  display: none; /* Hidden by default */
  position: fixed; /* Stay in place */
  z-index: 1; /* Sit on top */
  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/Box */
.modal-content {
  background-color: #fefefe;
  margin: 15% auto; /* 15% from the top and centered */
  padding: 20px;
  border: 1px solid #888;
  width: 80%; /* Could be more or less, depending on screen size */
}

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

.close:hover,
.close:focus {
  color: black;
  text-decoration: none;
  cursor: pointer;
}
<!-- Trigger/Open The Modal -->
<button id="myBtn">Open Modal</button>

<!-- Trigger/Open The Modal -->
<a id="myAnchor" href="#">Open Modal here as well</a>

<!-- 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>

Кредиты

CSS и HTML в Интернете фрагмент со страницы w3School, на которую ссылается OP.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...