在单击时使用纯JavaScript隐藏Bootstrap模式

Jon*_*Doe 5 javascript twitter-bootstrap

我正在研究Bootstrap Pop Up Modals。

我有2个名为Button1Button2的按钮。

我有两个名为Modal1Modal2的模态。

注:Button2的是里面的Modal1Button1的是对网页。

如果单击Button1,则Modal1应该为“打开”;如果单击Modal内的Button2,则Modal1应该自动隐藏,并显示Modal2。

我正在使用jQuery Yet&It正常工作。

<script>
$('#button1').click(function()
{
    $('#modal1').modal('hide');
    $('#modal2').modal('show');
});
</script>
Run Code Online (Sandbox Code Playgroud)

题:

我如何使用Pure JavaScript做到这一点。???????

Neb*_*sha 16

这是我编写的解决方法,目的是使用 DOM 操作关闭本机 Java 脚本中的模式。使用引导程序 4。

function closeAllModals() {

    // get modals
    const modals = document.getElementsByClassName('modal');

    // on every modal change state like in hidden modal
    for(let i=0; i<modals.length; i++) {
      modals[i].classList.remove('show');
      modals[i].setAttribute('aria-hidden', 'true');
      modals[i].setAttribute('style', 'display: none');
    }

     // get modal backdrops
     const modalsBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove every modal backdrop
     for(let i=0; i<modalsBackdrops.length; i++) {
       document.body.removeChild(modalsBackdrops[i]);
     }
  }
Run Code Online (Sandbox Code Playgroud)

所以这个函数会关闭页面上找到的所有模态。您可以修改它以根据 id 关闭某个特定模式。这边走:

function closeOneModal(modalId) {

    // get modal
    const modal = document.getElementById(modalId);

    // change state like in hidden modal
    modal.classList.remove('show');
    modal.setAttribute('aria-hidden', 'true');
    modal.setAttribute('style', 'display: none');

     // get modal backdrop
     const modalBackdrops = document.getElementsByClassName('modal-backdrop');

     // remove opened modal backdrop
      document.body.removeChild(modalBackdrops[0]);
  }
Run Code Online (Sandbox Code Playgroud)

所以,根本不知道 jQuery


Emm*_*kwe 6

您可以只id为通常会关闭/打开模态的按钮分配一个,模拟单击按钮以编程方式关闭/打开模态。

例如 - $('#modal1').modal('hide'); $('#modal2').modal('show');会变成 document.getElementById('modalX').click();


小智 5

遵循纯 JavaScript 代码对我的 bootstrap5 来说效果很好。

let myModalEl = document.getElementById('modal1')
let modal = bootstrap.Modal.getInstance(myModalEl)
modal.hide()
Run Code Online (Sandbox Code Playgroud)


小智 -3

你能试试这个吗....

function showmodel(){
var Modal1 = document.getElementById("Modal1"); 
Modal1.show(); 
}
function hidemodel1()
{
var Modal1 = document.getElementById("Modal1"); 
var Modal2 = document.getElementById("Modal2"); 
Modal1.hide(); 
Modal2.show(); 
}
Run Code Online (Sandbox Code Playgroud)

在按钮onclick中调用上述方法。