简体   繁体   English

如何打开具有相应 ID 的模态 div?

[英]How do i open the modal div with the corresponding ID?

I have a page with multiple modals, when i click a button for one of these modals, the first always opens.我有一个包含多个模式的页面,当我单击其中一个模式的按钮时,第一个总是打开。 The code used to work with Bootstrap 4.0, but I switched from bootstrap to Tailwind CSS.该代码用于 Bootstrap 4.0,但我从 bootstrap 切换到 Tailwind CSS。

The modal div has id="modal1" .模态 div 有id="modal1" The button has class="modal-open" and data-target="#modal1" .该按钮有class="modal-open"data-target="#modal1"

This is my javascript code:这是我的 javascript 代码:

var openmodal = document.querySelectorAll('.modal-open')
    for (var i = 0; i < openmodal.length; i++) {
      openmodal[i].addEventListener('click', function(event){
        event.preventDefault()
        toggleModal()
      })
    }

    const overlay = document.querySelector('.modal-overlay')
    overlay.addEventListener('click', toggleModal)

    var closemodal = document.querySelectorAll('.modal-close')
    for (var i = 0; i < closemodal.length; i++) {
      closemodal[i].addEventListener('click', toggleModal)
    }

    document.onkeydown = function(evt) {
      evt = evt || window.event
      var isEscape = false
      if ("key" in evt) {
        isEscape = (evt.key === "Escape" || evt.key === "Esc")
      } else {
        isEscape = (evt.keyCode === 27)
      }
      if (isEscape && document.body.classList.contains('modal-active')) {
        toggleModal()
      }
    };


    function toggleModal () {
      const body = document.querySelector('body')
      const modal = document.querySelector('.modal')
      modal.classList.toggle('opacity-0')
      modal.classList.toggle('pointer-events-none')
      body.classList.toggle('modal-active')
    }

When I click the button with data-target="modal3" , I want modal 3 to open, now modal 1 always opens.当我单击带有data-target="modal3"的按钮时,我希望打开模态 3,现在总是打开模态 1。

const modal = document.querySelector('.modal')

This line will always return the first occurrence of class 'modal', thus modal 1, assuming it comes first in the markup.此行将始终返回 class 'modal' 的第一次出现,即模态 1,假设它在标记中首先出现。 If you want toggleModal() to operate on another div, you will have to pass the ID of the div as an argument to toggleModal().如果您希望 toggleModal() 对另一个 div 进行操作,则必须将 div 的 ID 作为参数传递给 toggleModal()。

https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector https://developer.mozilla.org/en-US/docs/Web/API/Document/querySelector

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM