简体   繁体   English

如何以编程方式触发 Bootstrap 模态?

[英]How can I trigger a Bootstrap modal programmatically?

If I go here如果我在这里 go

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

And click 'Launch demo modal' it does the expected thing.然后单击“启动演示模式”,它会执行预期的操作。 I'm using the modal as part of my signup process and there is server side validation involved.我在注册过程中使用模式,并且涉及服务器端验证。 If there are problems I want to redirect the user to the same modal with my validation messages displayed.如果有问题,我想将用户重定向到显示我的验证消息的相同模式。 At the moment I can't figure out how to get the modal to display other than a physical click from the user.目前,除了用户的物理点击之外,我无法弄清楚如何让模态显示。 How can I launch the model programmatically?如何以编程方式启动 model?

In order to manually show the modal pop up you have to do this为了手动显示模式弹出你必须这样做

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

You previously need to initialize it with show: false so it won't show until you manually do it.您之前需要使用show: false对其进行初始化,因此在您手动执行之前它不会显示。

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

Where myModal is the id of the modal container.其中myModal是模态容器的 id。

You should't write data-toggle="modal" in the element which triggered the modal (like a button), and you manually can show the modal with:您不应该在触发模态的元素(如按钮)中写入data-toggle="modal" ,您可以手动显示模态:

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

and hide with:并隐藏:

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

If you are looking for a programmatical modal creation, you might love this:如果您正在寻找编程模式创建,您可能会喜欢这个:

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

Even though Bootstrap's modal provides a javascript way for modal creation, you still need to write modal's html markups first.尽管 Bootstrap 的 modal 提供了一种用于创建模态的 javascript 方式,您仍然需要先编写 modal 的 html 标记。

HTML 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 JS

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

DEMO JSFIDDLE演示 JSFIDDLE

you can show the model via jquery (javascript)您可以通过 jquery (javascript) 显示模型

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

Demo: here演示:这里

or you can just remove the class "hide"或者您可以删除“隐藏”类

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

I wanted to do this the angular (2/4) way, here is what I did:我想以angular (2/4)方式执行此操作,这是我所做的:

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

Important things to note :需要注意的重要事项

  • visible is a variable (boolean) in the component which governs modal's visibility. visible是组件中控制模态可见性的变量(布尔值)。
  • show and in are bootstrap classes. showin是引导类。

An example component & html一个示例组件html

Component成分

@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 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-->

This is a code for Bootstrap v5 without jQuery .这是没有 jQuery 的Bootstrap v5的代码。

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

Demo演示

And this is a codesandbox demo to open modal on page load programmatically.这是一个以编程方式打开页面加载模式的代码演示。

https://idu6i.csb.app/ https://idu6i.csb.app/

Refs参考资料

The following code useful to open modal on openModal() function and close on closeModal() :以下代码可用于在 openModal() 函数上打开模态并在 closeModal() 上关闭:

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

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

/* #myModal is the id of modal popup */ /* #myModal 是模态弹出窗口的 id */

The same thing happened to me.这样的事情我也经历过。 I wanted to open the Bootstrap modal by clicking on the table rows and get more details about each row.我想通过单击表格行来打开 Bootstrap 模式并获取有关每一行的更多详细信息。 I used a trick to do this, Which I call the virtual button!我使用了一个技巧来做到这一点,我称之为虚拟按钮! Compatible with the latest version of Bootstrap (v5.0.0-alpha2).与最新版本的 Bootstrap (v5.0.0-alpha2) 兼容。 It might be useful for others as well.它可能对其他人也有用。

See this code snippet with preview: https://gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba请参阅此代码片段预览: https : //gist.github.com/alireza-rezaee/c60da1429c36351ef4f071dec0ea9aba

Summary:概括:

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

All this is to use the relatedTarget property.所有这些都是为了使用relatedTarget属性。 (See Bootstrap docs ) (参见Bootstrap 文档

Here's how you do it with ternary operator这是使用三元运算符的方法

$('#myModal').modal( variable === 'someString' ? 'show' : 'hide');

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

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