【问题标题】:Hide Bootstrap Modal using Pure JavaScript On Click单击时使用纯 JavaScript 隐藏引导模式
【发布时间】:2017-10-05 04:06:56
【问题描述】:

我正在研究 Bootstrap 弹出模式。

我有 2 个按钮,分别命名为 Button1Button2

&

我有 2 个名为 Modal1Modal2 的模态。

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

如果我点击 Button1Modal1 应该是 Open & 如果我点击 Modal 内部的 Button2 ,那么 Modal1 应该会自动隐藏并且应该显示 Modal2。

我正在使用 jQuery 做这件事,但它工作正常。

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

问题:

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

【问题讨论】:

  • 您可以通过多种方式使用纯 JS 创建“模态” - 按需生成 HTML 元素并将它们注入 DOM,在现有 DOM 节点上操作类等。这只是一个,第一个代码示例 i在google中搜索“modal pure javascript”后发现:codepen.io/bsngr/pen/yJWJWw
  • 这不是我要问的。
  • 那么您是在寻找适合您需求的工作代码吗? StackOverflow 是为了解决问题,而不是为别人工作。

标签: javascript twitter-bootstrap


【解决方案1】:

这是我编写的解决方法,目的是使用 DOM 操作在本机 Java 脚本中关闭模式。使用 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 关闭某个特定模式。这样:

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。唯一的问题是页面在模式关闭后仍然处于非活动状态(用户必须单击一次才能使其再次处于活动状态)。关于如何在函数内部执行此操作的任何线索?
  • 我在 bootstrap modal 和 jquery modal 之间发生了冲突,现在有了这个功能,我可以关闭任何 modal
  • @Muriel 我的第一个疯狂猜测是背景没有正确关闭。请检查您的版本中的类名是否仍然是“模态背景”。或者,也许您有多个背景,因此其中一些保持打开状态。在这种情况下,您应该遍历所有 modalBackdrops 并关闭它们。
【解决方案2】:

您可以将id 分配给通常会关闭/打开模式的按钮,模拟单击按钮以编程方式关闭/打开模式。

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

【讨论】:

    【解决方案3】:

    这是一个可行的解决方案:

    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");
    

    【讨论】:

      【解决方案4】:

      您可以使用 javascript 创建一个“模态”元素。优点是可以重复使用。我已经使用 javascript 创建了一个示例引导模式。您可以对其进行修改以添加更多功能。

      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() 将隐藏相同

      这可以用作引导模式的通用模板。

      【讨论】:

        【解决方案5】:

        遵循纯 javascript 代码适用于我的 bootstrap5。

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

        【讨论】:

          【解决方案6】:

          这是在纯 JS 中获取 modal.hide()(以及所有其他模态方法!)的方法。
          您可以在官方文档页面上试用,这里以modal documentation 为例。 问题是,模态在模态 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();
          

          【讨论】:

            【解决方案7】:

            你能试试这个吗....

            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中调用上述方法

            【讨论】:

              猜你喜欢
              • 2021-03-24
              • 2015-06-27
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2019-03-31
              相关资源
              最近更新 更多