点击时使用纯JavaScript隐藏Bootstrap模态框

12

我正在处理Bootstrap弹出模态框。

我有两个名为Button1Button2的按钮。

&

我有两个名为Modal1Modal2的模态框。

注意:Button2Modal1内,Button1在网页上。

如果我点击Button1,则应该打开Modal1。如果我点击模态框内的Button2,则Modal1应该自动隐藏,然后显示Modal2。

我正在使用jQuery实现它,并且它运行正常。

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

问题:

如何使用纯JavaScript实现它? ???????


你可以用纯JS以多种方式创建“模态窗口” - 根据需要生成HTML元素并将它们注入到DOM中,或者在已存在的DOM节点上操作类等。这里是在谷歌搜索“modal pure javascript”后找到的第一个代码示例:https://codepen.io/bsngr/pen/yJWJWw - Adam Szmyd
1
这不是我所询问的内容。 - Jone Doe
你是在寻求符合你需求的可用代码吗?StackOverflow旨在解决问题,而不是为他人创造工作。 - Adam Szmyd
8个回答

24

这里是我为了关闭原生Java Script中的模态框而编写的解决方案,使用DOM操作。使用Bootstrap 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]);
     }
  }

所以这个函数关闭页面上找到的所有模态框。您可以根据id修改它以关闭某个特定的模态框。方法如下:

因此,该函数将关闭页面上找到的所有模态框。您可以根据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]);
  }

所以,完全没有jQuery的线索


非常感谢您的回答,@Nebojsha。唯一的问题是在关闭模态框后页面仍然保持不活动状态(用户必须单击一次才能使其再次活动)。有关如何在函数内部解决此问题的线索吗? - Muriel
我曾经在Bootstrap模态框和jQuery模态框之间发生了冲突,但现在有了这个函数,我可以关闭任何模态框。 - devseo
@Muriel 我的第一个猜测是背景没有正确关闭。请检查您的版本中类名是否仍为“modal-backdrop”。 或者,您可能有多个背景,因此其中一些保持打开状态。在这种情况下,您应该遍历所有modalBackdrops并将它们关闭。 - Nebojsha
谢谢这个解决方案!对于我的用例,所有的引导方法都不起作用,这让我疯了。老实说,纯粹的JS才是最好的选择! - Christine Treacy

8

您可以为通常用于关闭/打开模态框的按钮分配一个id,然后模拟单击该按钮来以编程方式关闭/打开模态框。

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


1
我特意登录来说这很棒! - nondeterministic

4

使用纯 JavaScript 代码对我的 Bootstrap5 功能正常。

let myModalEl = document.getElementById('modal1')
let modal = bootstrap.Modal.getInstance(myModalEl)
modal.hide()

解决了问题。谢谢。 - Abpostman1

2

以下是可行的解决方案:

https://codepen.io/hamzeen/pen/MErYgp

您可以在不写任何JavaScript代码的情况下实现它,但我找不到使用纯JavaScript的方法。锚点标签上的data-target属性处理切换功能,请查看下面的代码:

<a href="#" class="btn btn-lg btn-danger" data-toggle="modal" data-
target="#modal1">Open Modal 1</a>

我在Bootstrap的Javascript库中发现了以下内容,这可能会对你有所帮助!
/*!
 * Bootstrap v3.3.7 (http://getbootstrap.com)
 * Copyright 2011-2016 Twitter, Inc.
 * Licensed under the MIT license
 */
if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript 
requires jQuery");

1

您可以使用 JavaScript 创建“模态”元素。优点是您可以重复使用它。我已经使用 JavaScript 创建了一个示例 Bootstrap 模态框。您可以修改它以添加更多功能。

var Interface = {};
Interface.component = function ( dom ) {
    this.dom = dom;
};
Interface.component.prototype = {
    setId: function ( id ) {
        this.dom.id = id;
        return this;
    }
    // you can add more common functions here
};

Interface.BootstrapModal = function ( id, modalHeading, modalBodyContents, successButtonText, failureButtonText ) {

    var scope = this;
    var dom = document.createElement( 'div' );
    dom.className = 'modal fade';
    dom.id = id;
    dom.role = "dialog";

    var modalDialog = document.createElement( 'div' );
    modalDialog.className = 'modal-dialog';

    var modalContent = document.createElement( 'div' );
    modalContent.className = 'modal-content';

    var modalHeader = document.createElement( 'div' );
    modalHeader.className = 'modal-header';

    var modalHeaderXButton = document.createElement( 'button' );
    modalHeaderXButton.className = 'close';
    modalHeaderXButton.setAttribute("data-dismiss", "modal");
    modalHeaderXButton.innerHTML = '&times';

    var modalHeaderHeading = document.createElement( 'h3' );
    modalHeaderHeading.className = 'modal-title';
    modalHeaderHeading.innerHTML = modalHeading;

    modalHeader.appendChild(modalHeaderXButton);
    modalHeader.appendChild(modalHeaderHeading);

    var modalBody = document.createElement( 'div' );
    modalBody.className = 'modal-body';
    modalBody.appendChild(modalBodyContents);

    var modalFooter = document.createElement( 'div' );
    modalFooter.className = 'modal-footer';

    var modalFooterSuccessButton = document.createElement( 'button' );
    modalFooterSuccessButton.className = 'btn btn-success';
    modalFooterSuccessButton.id = "<GIVE THE ID YOU NEED>";
    //modalFooterSuccessButton.setAttribute("data-dismiss", "modal");
    modalFooterSuccessButton.innerHTML = successButtonText;

    var modalFooterFailureButton = document.createElement( 'button' );
    modalFooterFailureButton.className = 'btn btn-danger';
    modalFooterFailureButton.id = "<GIVE THE ID YOU NEED>";
    modalFooterFailureButton.setAttribute("data-dismiss", "modal");
    modalFooterFailureButton.innerHTML = failureButtonText;

    modalFooter.appendChild(modalFooterSuccessButton);
    modalFooter.appendChild(modalFooterFailureButton);

    modalContent.appendChild(modalHeader);
    modalContent.appendChild(modalBody);
    modalContent.appendChild(modalFooter);
    modalDialog.appendChild(modalContent);

    dom.appendChild(modalDialog);

    modalFooterSuccessButton.addEventListener( 'click', function ( event ) {

        // perform your actions

    } );

    this.dom = dom;
    return this;

};

Interface.BootstrapModal.prototype = Object.create( Interface.component.prototype );
Interface.BootstrapModal.prototype.constructor = Interface.BootstrapModal;

Interface.BootstrapModal.prototype.show = function () {

    $('#' + this.dom.id).modal({backdrop: 'static', keyboard : false});

};

Interface.BootstrapModal.prototype.hide = function () {

    $('#' + this.dom.id).modal('hide');

};

我创建了一个对象作为模态框元素。你可以像这样使用它:

var modalContent = document.createElement( 'div' );
var m = new Interface.BootstrapModal( 'id', 'modalHeading', modalContent, 'successButtonText', 'cancelButtonText' );
document.getElementById( <SOME ELEMENT> ).appendChild( m.dom );

现在m.show()将显示模态框,m.hide()将隐藏相同的模态框。

这可以用作Bootstrap模态框的通用模板。


0

以下是如何在纯JS中获取modal.hide()(以及所有其他modal方法!)的方法。
您可以在官方文档页面上尝试,让我们以modal documentation为例。 关键是,modal DOM对象上存储了一个类似于“jQuery331042511280243656492”的属性。此属性包含所有modal方法! 只需先打开此模态框,然后在控制台中运行代码即可。

更新:该jQuery对象仅附加在第一次打开模态框时,并且从那时起一直存在。这意味着,除非我们已经至少打开过一次模态框,否则我们无法通过此方法“.show()”我们的模态框。

    // get reference to the modal. It's 'div.modal', in general
    var modal = document.querySelector('#exampleModalLong');
    // get the key under which the modal's methods are stored.
    var jQueryObj = Object.keys(modal).filter((key) => (key.toString().indexOf('jQuery') !== -1) && modal[key].hasOwnProperty('bs.modal'));
    // ... and close the modal!
    modal[jQueryObj]['bs.modal'].hide();

0
//Get modal
const bs_modal = document.getElementById(modalId);

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

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

//Remove opened modal backdrop
document.body.removeChild(modalBackdrops[0]);

-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(); 
}

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接