Включите якорь в свой 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">×</span>
<p>Some text in the Modal..</p>
</div>
</div>
Кредиты
CSS и HTML в Интернете фрагмент со страницы w3School, на которую ссылается OP.