Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
118 views
in Technique[技术] by (71.8m points)

javascript - Modal adding/removing

HTML:

 <!-- hero  -->
      <div class="hero">
        <div class="banner">
          <h1>Modal</h1>
          <button class="btn modal-btn">open modal</button>
        </div>
      </div>
      <!-- end of hero  -->
      <!-- modal  -->
      <div class="modal-overlay">
        <div class="modal-container">
          <h4>
            Some lorem
          </h4>
          <button class="close-btn">
            <i class="fas fa-times"></i>
          </button>
        </div>
        <!-- end of modal  -->

CSS:

.modal-overlay {
  /*Some css codes to modify overlay*/
  visibility: hidden;
  z-index: -10;
}
.open-modal {
  visibility: visible;
  z-index: 10;
}

JS:

const btnModal = document.querySelector('.modal-btn');
const overlayModal = document.querySelector('.modal-overlay');
const btnCloseModal = document.querySelector('.close-btn');
function openModal(){
  overlayModal.classList.add('open-modal')
}
function closeModal(){
  overlayModal.classList.remove('open-modal')
}
btnModal.addEventListener('click',openModal)
btnCloseModal.addEventListener('click', closeModal)
  1. Is it the most efficient way for modals?
  2. How .open-modal overwrites .modal-overlay's properties? Sometimes it worked for me, sometimes not. What do I need to give attention?
question from:https://stackoverflow.com/questions/65645180/modal-adding-removing

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
  1. Yes, it is. People usually use display: block and display: none. But visibilty also okay.

  2. Your class aren't removed. You can try to use, if this resolve your problem

element.style.display = 'block' //

Here some references https://gomakethings.com/two-ways-to-set-an-elements-css-with-vanilla-javascript/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...