2014-08-29 222 views
6

我很努力在设定的时间段后自动关闭Bootstrap模态。如何在时间段后自动关闭Bootstrap 3模态

下面是我使用关闭模式在4秒的JS代码:

setTimeout(function() { $('#myModal').modal('hide'); }, 4000);

两个基本问题:

(A)当HTML页面(包含情态动词)载荷,模态超时似乎在模态被显示之前运行。模式设置为在点击页面中的链接后显示。如果没有点击链接立即当页面加载时,模式将只会短暂出现,然后立即关闭,因为实质上超时时段是在加载html页面时开始的,而不是在显示模式时。 (B)如果用户第二次(或第三次,第四次等)点击链接启动模式,模式将正常显示,但在该时间段后不会关闭。它只是保持打开状态,直到用户手动关闭它。

所以......这两个问题是:

(1)如何获得模态超时时间要等到模式运行时钟之前显示。 (2)如何让适当的Timeout函数仍然有效的第二次和第三次显示模式?

(在这个环节中提出的答案(S)低于看起来前途无量,但不是为我工作。也许他们不引导3?How to automatically close the bootstrap modal dialog after a minute工作)

下面这段代码看起来非常有前途的,但即使在将“显示”更改为“shown.bs.modal”后也不起作用。或者,也许我把这个代码放在错误的地方?

var myModal = $('#myModal').on('shown', function() { 
    clearTimeout(myModal.data('hideInteval')) 
    var id = setTimeout(function(){ 
     myModal.modal('hide'); 
    }); 
    myModal.data('hideInteval', id); 
}) 

非常感谢您的任何建议!

+0

在引导3模态事件后缀,所以你应该使用'shown.bs.modal',而不是'show',也就是对一个评论您链接的答案 – 2014-08-29 23:55:43

回答

8

我想这取决于你如何显示你的模态。但是你可以在事件监听器中设置超时时间?

这里是一个JSFiddle来演示如何实现它。基本上你会在事件发生时执行的函数中添加超时。

// Select the element you want to click and add a click event 
$("#your-link").click(function(){ 
    // This function will be executed when you click the element 
    // show the element you want to show 
    $("#the-modal").show(); 

    // Set a timeout to hide the element again 
    setTimeout(function(){ 
     $("#the-modal").hide(); 
    }, 3000); 
}); 

如果监听的事件是你可以有使用event.preventDefault()防止默认动作过于链接的点击。你可以找到更多的信息here

我希望这会有所帮助。

+0

您可以将其用作: setTimeout(function(){$('#myModal')。modal('hide')},3000); – 2016-04-18 10:16:41

10

我不是很肯定你的HTML,所以我做了一个完整的例子:

HTML:

<a data-toggle="modal" href="#myModal" class="btn btn-primary">Open Modal</a> 

<div id="myModal" class="modal fade"> 
    <div class="modal-dialog"> 
     <div class="modal-content"> 
      <div class="modal-header"> 
       <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button> 
       <h4>Header</h4> 
      </div> 
      <div class="modal-body"> 
       Modal Content 
      </div> 
     </div> 
    </div> 
</div> 

JS:

$(function(){ 
    $('#myModal').on('show.bs.modal', function(){ 
     var myModal = $(this); 
     clearTimeout(myModal.data('hideInterval')); 
     myModal.data('hideInterval', setTimeout(function(){ 
      myModal.modal('hide'); 
     }, 3000)); 
    }); 
}); 

与您的代码的主要区别:

  1. 我设置了超时时间(300 0)
  2. 我设置myModal变量中 回调现在
+0

为我工作感谢! – denis 2017-11-21 13:21:59

相关问题