显示模态时,Twitter Bootstrap模态事件未触发

根据文件:

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

它应该触发方法“show.bs.dropdown”和“shown.bs.dropdown”。 但它没有:

http://jsfiddle.net/mQunq/3/

HTML:

 

jQuery的:

 // show.bs.modal doesn't work either $('#myModal') .modal('show') .on('show.bs.modal', function() { alert('shown baby!'); }); 

你需要先注册事件然后触发它

 $('#myModal') .on('show.bs.modal', function() { alert('shown baby!'); }).modal('show'); 

的jsfiddle

当它发生时

当modal也有类“淡入淡出”时,不会触发事件显示 .bs.modal。 而show .bs.modal始终有效。 请参阅https://github.com/twbs/bootstrap/issues/11793

HTML:

   

jQuery的:

 $('.modal').on('shown.bs.modal', function() { //fired only in second modal console.info('shown.bs.modal'); }); $('.modal').on('show.bs.modal', function() { //fired always console.info('show.bs.modal'); }); 

对于bootstrap v3.3.6,将line 1010替换为:

 that.$element // wait for modal to slide in 

问题是什么

看看第1006-1015行:

  var e = $.Event('shown.bs.modal', { relatedTarget: _relatedTarget }) transition ? that.$dialog // wait for modal to slide in .one('bsTransitionEnd', function () { that.$element.trigger('focus').trigger(e) }) .emulateTransitionEnd(Modal.TRANSITION_DURATION) : that.$element.trigger('focus').trigger(e) 

没有转换(没有淡入淡出类),事件e立即被触发(在那个。$元素上)。 有了转换,我不确定为什么,但不知何故来自函数emulateTransitionEndbsTransationEnd事件不会被处理。$ dialog.one() 。 但有了这个。$元素 ,一切似乎都有效。

类似的事情发生在我身上,我已经使用setTimeout解决了。

Bootstrap使用以下超时来完成显示:

c.TRANSITION_DURATION = 300,c.BACKDROP_TRANSITION_DURATION = 150,

所以使用超过300个必须工作,对我来说200工作:

 $('#myModal').on('show.bs.modal', function (e) { setTimeout(function(){ //Do something if necessary }, 300); }) 

你忘记了显示的“n”

 $(document).ready(function(){ $('#myModal') .modal('show') .on('shown.bs.modal', function() { alert('shown baby!'); }); }); 

使用文档而不是自定义选择器。 shows.bs.modal和show.bs.modal都工作得很好

 $(document).on('shown.bs.modal', '.modal', function() { alert(); }); 

如果有人偶然发现了这个问题,请确保触发模态的toggle 之前挂钩hidden / shown事件。 也就是说,声明:

 $("#selector").on("hidden.bs.modal", function () { // do the right thing }); 

在调用模态的切换之前,例如:

 ("#selector").modal("toggle"); 

我知道这是基本的,但在复杂的代码中它会发生。

我找到了一个与.fade过渡一起使用的解决方案:

 $(document).on($.support.transition.end, '.modal.fade.in', function(e) { var $target = $(e.target); if ($(e.target).is(".modal-dialog")) { console.log("Modal Shown") } }); $(document).on($.support.transition.end, '.modal.fade', function(e) { var $target = $(e.target); if (!$target.is(".modal.fade.in") && !$target.is(".modal-dialog")) { console.log("Modal Hidden") } }); 

如果您的模态是动态创建的,请选择最接近的静态父元素,并将您的模态作为参数添加到bootstrap模态事件中:

 /* body is static, .modal is not */ $("body").on('shown.bs.modal', '.modal', function() { alert('shown'); }); $("body").on('hidden.bs.modal', '.modal', function() { alert('hidden'); }); $("body").on('show.bs.modal', '.modal', function() { alert('show'); }); $("body").on('hide.bs.modal', '.modal', function() { alert('hide'); });