【问题标题】:How can I trigger a Bootstrap modal programmatically?如何以编程方式触发 Bootstrap 模式?
【发布时间】:2012-07-09 10:07:14
【问题描述】:

如果我去这里

http://getbootstrap.com/2.3.2/javascript.html#modals

然后单击“启动演示模式”,它会执行预期的操作。我在注册过程中使用模式,并且涉及服务器端验证。如果有问题,我想将用户重定向到显示验证消息的相同模式。目前,除了用户的物理点击之外,我无法弄清楚如何让模式显示。如何以编程方式启动模型?

【问题讨论】:

    标签: javascript twitter-bootstrap


    【解决方案1】:

    为了手动显示模式弹出窗口,您必须这样做

    $('#myModal').modal('show');
    

    您之前需要使用show: false 对其进行初始化,因此在您手动执行之前它不会显示。

    $('#myModal').modal({ show: false})
    

    myModal 是模态容器的 id。

    【讨论】:

    • 谢谢。那成功了。然而,一个观察结果是,当我打开模式框时,它会重置滚动,如果我从页面底部触发模式框,页面会滚动到顶部。我应该如何阻止它?
    • @tdubs:很奇怪,它应该可以工作。见最新模态代码github.com/twitter/bootstrap/blob/master/js/bootstrap-modal.js。到目前为止,我看到它应该仍然有效
    • @ClaudioRedi,我在控制台中都试过了,我发现只有一个使用铬。 $('#myModal').modal({show: false}) 不起作用,但 $('#myModal').modal('hide') 起作用。不知道为什么
    • 有什么方法可以将自定义值或参数作为选项传递,例如 $('#myModel').model({data:1,show:false})
    • @divinedragon 年龄晚了我知道,但是滚动到页面顶部的问题可能是由于触发了带有'<a href='#'> 之类的标签的弹出窗口并且未能return falsepreventDefault处理程序内部。浏览器按照指示进行操作并滚动到默认锚点 - 页面顶部。我已经被这个咬了好几次了,因为我们的 CSS 有时依赖于设置 href 来匹配样式。
    【解决方案2】:

    您不应该在触发模态的元素(如按钮)中编写 data-toggle="modal",您可以手动显示模态:

    $('#myModal').modal('show');
    

    并隐藏:

    $('#myModal').modal('hide');
    

    【讨论】:

    • 我有一个使用数据切换打开模式的 URL。然后在模态中,我有一个按钮,它调用一个函数,它所做的最后一件事是使用您建议的 hide 方法关闭模态。太好了!
    【解决方案3】:

    如果您正在寻找程序化模态创建,您可能会喜欢这个:

    http://nakupanda.github.io/bootstrap3-dialog/

    尽管 Bootstrap 的 modal 提供了一种 javascript 的方式来创建 modal,但您仍然需要先编写 modal 的 html 标记。

    【讨论】:

      【解决方案4】:

      HTML

      <!-- Button trigger modal -->
      <button type="button" class="btn btn-primary btn-lg">
        Launch demo modal
      </button>
      
      <!-- Modal -->
      <div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
        <div class="modal-dialog">
          <div class="modal-content">
            <div class="modal-header">
              <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button>
              <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
              ...
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
              <button type="button" class="btn btn-primary">Save changes</button>
            </div>
          </div>
        </div>
      </div>
      

      JS

      $('button').click(function(){
      $('#myModal').modal('show');
      });
      

      DEMO JSFIDDLE

      【讨论】:

        【解决方案5】:

        您可以通过 jquery (javascript) 显示模型

        $('#yourModalID').modal({
          show: true
        })
        

        演示:here

        或者您可以删除“隐藏”类

        <div class="modal" id="yourModalID">
          # modal content
        </div>
        

        【讨论】:

          【解决方案6】:

          我想以angular (2/4) 的方式执行此操作,这就是我所做的:

          <div [class.show]="visible" [class.in]="visible" class="modal fade" id="confirm-dialog-modal" role="dialog">
          ..
          </div>`
          

          注意的重要事项:

          • visible 是组件中控制模态可见性的变量(布尔值)。
          • showin 是引导类。

          一个例子component & html

          组件

          @ViewChild('rsvpModal', { static: false }) rsvpModal: ElementRef;
          ..
          @HostListener('document:keydown.escape', ['$event'])
            onEscapeKey(event: KeyboardEvent) {
              this.hideRsvpModal();
            }
          ..
            hideRsvpModal(event?: Event) {
              if (!event || (event.target as Element).classList.contains('modal')) {
                this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'none');
                this.renderer.removeClass(this.rsvpModal.nativeElement, 'show');
                this.renderer.addClass(document.body, 'modal-open');
              }
            }
            showRsvpModal() {
              this.renderer.setStyle(this.rsvpModal.nativeElement, 'display', 'block');
              this.renderer.addClass(this.rsvpModal.nativeElement, 'show');
              this.renderer.removeClass(document.body, 'modal-open');
            }
          

          HTML

          <!--S:RSVP-->
          <div class="modal fade" #rsvpModal role="dialog" aria-labelledby="niviteRsvpModalTitle" (click)="hideRsvpModal($event)">
              <div class="modal-dialog modal-dialog-centered modal-dialog-scrollable" role="document">
                  <div class="modal-content">
                      <div class="modal-header">
                          <h5 class="modal-title" id="niviteRsvpModalTitle">
          
                          </h5>
                          <button type="button" class="close" (click)="hideRsvpModal()" aria-label="Close">
                              <span aria-hidden="true">&times;</span>
                          </button>
                      </div>
                      <div class="modal-body">
          
                      </div>
                      <div class="modal-footer">
                          <button type="button" class="btn btn-secondary bg-white text-dark"
                              (click)="hideRsvpModal()">Close</button>
                      </div>
                  </div>
              </div>
          </div>
          <!--E:RSVP-->
          

          【讨论】:

            【解决方案7】:

            这是 Bootstrap v5 without jQuery的代码。

            let myModal = new bootstrap.Modal(document.getElementById('myModal'), {});
            myModal.show();
            

            演示

            这是一个codesandbox 演示,用于以编程方式在页面加载时打开模式。

            https://idu6i.csb.app/

            参考

            【讨论】:

              【解决方案8】:

              以下代码可用于在 openModal() 函数上打开模态并在 closeModal() 上关闭:

                    function openModal() {
                        $(document).ready(function(){
                           $("#myModal").modal();
                        });
                    }
              
                   function closeModal () {
                        $(document).ready(function(){
                           $("#myModal").modal('hide');
                        });  
                    }
              

              /* #myModal 是模态弹窗的id */

              【讨论】:

              • 请解释发布答案时代码的作用。
              【解决方案9】:

              同样的事情也发生在我身上。我想通过单击表格行来打开 Bootstrap 模式并获取有关每一行的更多详细信息。我使用了一个技巧来做到这一点,我称之为虚拟按钮!兼容最新版本的 Bootstrap (v5.0.0-alpha2)。它可能对其他人也有用。

              查看此代码 sn-p 预览: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

              总结:

              let exampleButton = document.createElement("button");
              exampleButton.classList.add("d-none");
              document.body.appendChild(exampleButton);
              exampleButton.dataset.toggle = "modal";
              exampleButton.dataset.target = "#exampleModal";
              
              //AddEventListener to all rows
              document.querySelectorAll('#exampleTable tr').forEach(row => {
                  row.addEventListener('click', e => {
                      //Set parameteres (clone row dataset)
                      exampleButton.dataset.whatever = e.target.closest('tr').dataset.whatever;
                      //Button click simulation
                      //Now we can use relatedTarget
                      exampleButton.click();
                  })
              });
              

              这一切都是为了使用relatedTarget 属性。 (见Bootstrap docs

              【讨论】:

              • 我不得不使用:dataset.bsToggledataset.bsTarget 而不是 dataset.toggledataset.target
              猜你喜欢
              • 2017-07-15
              • 2014-04-22
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2010-12-16
              • 1970-01-01
              相关资源
              最近更新 更多