关闭Bootstrap模态

时间:2013-05-11 02:49:24

标签: jquery twitter-bootstrap modal-dialog

我有一个我想要最初显示的引导模式对话框,然后当用户点击页面时,它会消失。我有以下内容:

$(function () {
   $('#modal').modal(toggle)
});

 <div class="modal" id='modal'>
     <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
        <h3 id="myModalLabel">Error:</h3>
        </div>
        <div class="modal-body">
        <p>Please correct the following errors:</p>
        </div>
     </div>
 </div>

最初显示模态,但在模态外部单击时不会关闭。此外,内容区域不会显示为灰色..如何让模式最初显示,然后在用户点击区域外关闭?如何在演示中将背景变为灰色?

25 个答案:

答案 0 :(得分:605)

modal('toggle')代替modal(toggle)

$(function () {
   $('#modal').modal('toggle');
});

答案 1 :(得分:359)

关闭bootstrap modal您可以将'hide'作为模式方法的选项传递如下

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

请查看 fiddle here

bootstrap还提供了可以挂钩到modal功能的事件,就像你想要在模式完成对用户隐藏时触发事件你可以使用 hidden.bs.modal 事件您可以在 Documentation

中详细了解模态方法和事件

如果以上方法都不起作用,请为关闭按钮指定一个ID并触发单击关闭按钮。

答案 2 :(得分:62)

$('#modal').modal('toggle'); 

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

应该有用。

但如果没有其他工作可以直接调用模态关闭按钮:

$("#modal .close").click()

答案 3 :(得分:30)

这对我有用:

<span class="button" data-dismiss="modal" aria-label="Close">cancel</span>

使用此链接modal close

答案 4 :(得分:10)

这个非常好,它也适用于角度2

$("#modal .close").click()

答案 5 :(得分:7)

我对这个问题的五分钱是我不想用id来定位自举模态并且看到一次应该只有一个模态,以下应该足以删除模态因为切换可能很危险:

$('.modal').removeClass('show');

答案 6 :(得分:7)

在某些情况下,输入错误可能是罪魁祸首。例如,请确保您拥有:

  /**
   * Convert a millisecond duration to a string format
   * 
   * @param millis A duration to convert to a string form
   * @return A string of the form "X Days Y Hours Z Minutes A Seconds B Milliseconds".
   */
   public static String getDurationBreakdown(long millis) {
       if (millis < 0) {
          throw new IllegalArgumentException("Duration must be greater than zero!");
       }

       long days = TimeUnit.MILLISECONDS.toDays(millis);
       long hours = TimeUnit.MILLISECONDS.toHours(millis) % 24;
       long minutes = TimeUnit.MILLISECONDS.toMinutes(millis) % 60;
       long seconds = TimeUnit.MILLISECONDS.toSeconds(millis) % 60;
       long milliseconds = millis % 1000;

       return String.format("%d Days %d Hours %d Minutes %d Seconds %d Milliseconds",
                            days, hours, minutes, seconds, milliseconds);
   }

而不是

data-dismiss="modal"

注意第二个示例中的双“ss”将导致“关闭”按钮失败。

答案 7 :(得分:6)

我们可以通过以下方式关闭模式弹出窗口:

// We use data-dismiss property of modal-up in html to close the modal-up,such as

<div class='modal-footer'><button type='button' class="btn btn-default" data-dismiss='modal'>Close</button></div>

 // We can close the modal pop-up through java script, such as

 <div class='modal fade pageModal'  id='openModal' tabindex='-1' data-keyboard='false' data-backdrop='static'>

    $('#openModal').modal('hide'); //Using modal pop-up Id.
    $('.pageModal').modal('hide'); //Using class that is defined in modal html.

答案 8 :(得分:5)

&#13;
&#13;
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script>
$(window).load(function(){
      $('#myModal').modal('show');
});
$(function () {
   $('#modal').modal('toggle');
});
</script>
</head>
<body>

<div class="container">
  <h2>Modal Example</h2>
  <!-- Trigger the modal with a button -->
  <button type="button" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal">Open Modal</button>

  <!-- Modal -->
  <div class="modal fade" id="myModal" role="dialog">
    <div class="modal-dialog">
    
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>
        <div class="modal-body">
          <p>Some text in the modal.</p>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
      
    </div>
  </div>
  
</div>

</body>
</html>
&#13;
&#13;
&#13;

答案 9 :(得分:5)

   function Delete(){
       var id = $("#dgetid").val();
       debugger
       $.ajax({
           type: "POST",
           url: "Add_NewProduct.aspx/DeleteData",
           data: "{id:'" + id + "'}",
           datatype: "json",
           contentType: "application/json; charset=utf-8",
           success: function (result) {
               if (result.d == 1) {
                   bindData();
                   setTimeout(function(){ $('#DeleteModal').modal('hide');},1000);
               }
           }
       });
   };

答案 10 :(得分:4)

$('.modal.in').modal('hide');

如果您在一个页面中使用多个模式弹出窗口,请使用上面的代码隐藏模态的背景。

答案 11 :(得分:4)

你可以使用;

$('#' + $('.modal.show').attr('id')).modal('hide');

答案 12 :(得分:4)

您可以看到this reference,但如果此链接已删除,请阅读以下说明:

使用一行JavaScript调用ID为myModal的模式:

$('#myModal').modal(options)

选项

可以通过数据属性或JavaScript传递选项。对于数据属性,将选项名称附加到 data- ,如 data-backdrop =“” 。< / p>

|-----------|-------------|--------|---------------------------------------------|
| Name      | Type        | Default| Description                                 |
|-----------|-------------|--------|---------------------------------------------|
| backdrop  | boolean or  | true   | Includes a modal-backdrop element.          |
|           | the string  |        | Alternatively, specify static for a         |
|           | 'static'    |        | backdrop which doesn't close the modal      |
|           |             |        | on click.                                   |
|           |             |        |                                             |
| keyboard  | boolean     | true   | Closes the modal when escape key is pressed.|   
|           |             |        |                                             |
| focus     | boolean     | true   | Puts the focus on the modal when initialized|       
|           |             |        |                                             |
| show      | boolean     | true   | Shows the modal when initialized.           |
|-----------|-------------|--------|---------------------------------------------|

方法

异步方法和转换

所有API方法都是异步的,并开始过渡。他们回来了 转换开始后但在转换结束之前立即将其发送给呼叫者。 此外,在过渡组件上的方法调用将是 忽略。

See our JavaScript documentation for more information.

.modal(options)

以模式形式激活您的内容。接受可选的options对象。

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

.modal('toggle')

手动切换模式。 在实际显示或隐藏模式之前返回调用者(即在show.bs.modal或hidden.bs.modal事件发生之前)。

$('#myModal').modal('toggle')

.modal('show')

手动打开模式。 在实际显示模式之前返回呼叫者(即在show.bs.modal事件发生之前)。

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

.modal('hide')

手动隐藏模式。 在实际隐藏模式之前返回调用者(即,在hidden.bs.modal事件发生之前)。

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

.modal('handleUpdate')

如果模态的高度在打开时发生变化(即,如果出现滚动条),则手动重新调整模态的位置。

$('#myModal').modal('handleUpdate')

.modal('dispose')

销毁元素的模态。

事件

Bootstrap的模态类公开了一些事件,可以挂接到模态功能上。所有模态事件均以模态本身(即**)触发。 类型说明

|----------------|--------------------------------------------------------------|
| Event Type     | Description                                                  |
|----------------|--------------------------------------------------------------|
| show.bs.modal  | This event fires immediately when the **show** instance      |
|                | method is called. If caused by a click, the clicked element  |
|                | is available as the **relatedTarget** property of the event. | 
|                |                                                              |
| shown.bs.modal | This event is fired when the modal has been made visible to  |
|                | the user (will wait for CSS transitions to complete). If     |
|                | caused by a click, the clicked element is available as the   | 
|                | **relatedTarget** property of the event.                     |
|                |                                                              |
| hide.bs.modal  | This event is fired immediately when the **hide** instance   |
|                | method has been called.                                      |
|                |                                                              |
| hidden.bs.modal| This event is fired when the modal has finished being hidden |
|                | from the user (will wait for CSS transitions to complete).   |
|----------------|--------------------------------------------------------------|

$('#myModal').on('hidden.bs.modal', function (e) {
  // do something...
})

答案 13 :(得分:3)

使用modal.hide只会隐藏模态。如果你在模态下使用叠加层,它仍然会存在。使用点击通话实际关闭模态并删除叠加。

$("#modalID .close").click()

答案 14 :(得分:3)

另一种方法是首先删除类modal-open,这将关闭模态。然后删除类模态背景,删除模态的灰色封面。

可以使用以下代码:

$('body').removeClass('modal-open')
$('.modal-backdrop').remove()  

答案 15 :(得分:2)

这段代码非常适合我关闭一个模态(我正在使用bootstrap 3.3)

$('#myModal').removeClass('in')

答案 16 :(得分:2)

在我的情况下,触发bootstrap模式的主页在使用$("#modal").modal('toggle');方式后开始没有响应,但是以下列方式开始响应:

$("#submitBtn").on("click",function(){
  $("#submitBtn").attr("data-dismiss","modal");
});

答案 17 :(得分:2)

  

我通过此技巧以编程方式关闭了模式

使用data-dismiss="modal"添加模式按钮,并使用display: none隐藏该按钮。这是它的样子

<div class="modal fade" id="addNewPaymentMethod" role="dialog">
  <div class="modal-dialog">
   .
   .
   .
   <button type="button" id="close-modal" data-dismiss="modal" style="display: none">Close</button>
  </div>
</div>

现在,当您想以编程方式关闭模式时,只需触发该按钮上的点击事件,该按钮对于用户是不可见的

在Javascript中,您可以像这样触发该按钮的点击:

document.getElementById('close-modal').click();

答案 18 :(得分:1)

只需将其添加为模态

div tabindex="-1"

答案 19 :(得分:1)

尝试一下

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

答案 20 :(得分:1)

这很好用

$(function () {
   $('#modal').modal('toggle');
});

但是,当您将多个模态相互叠加时,它是无效的,因此,它可以工作

data-dismiss="modal"

答案 21 :(得分:1)

此外,你可以点击&#34;在&#39; x&#39;上,关闭对话框。 E.g:

$(".ui-dialog-titlebar-close").click();

答案 22 :(得分:0)

就我而言,我使用了一个按钮来显示模式

<button type="button" class="btn btn-success" style="color:white"
    data-toggle="modal" data-target="#my-modal-to-show" >
    <i class="fas fa-plus"></i> Call MODAL
</button>

因此,在我的代码中,要关闭模式(具有id =“ my-modal-to-show”),我调用该函数(在Angular打字稿中):

closeById(modalId: string) {
  $(modalId).modal('toggle');
  $(modalId+ ' .close').click();
}

如果我调用$(modalId).modal('hide'),它将不起作用,而且我也不知道为什么

PS .:在我的模态中,我也使用.close类对该按钮元素进行了编码

<button type="button" class="close" data-dismiss="modal" aria-label="Close"> 
    <span aria-hidden="true">&times;</span>
</button>

答案 23 :(得分:0)

经过一些测试,我发现对于引导模态,在执行$(.modal).modal('hide')之后需要等待一段时间才能执行$(.modal).modal('show')。在我的情况下,我发现两者之间至少需要500毫秒的间隔。
这是我的测试用例和解决方案:

$('.modal-loading').modal('show');
setTimeout(function() {
  $('.modal-loading').modal('hide');
}, 500);

答案 24 :(得分:-2)

有时候解决方案无效,因此您必须正确删除in类并手动添加css display:none。

$("#modal").removeClass("in");
$("#modal").css("display","none");