【问题标题】:How to automatically close Bootstrap 3 modal after time period [duplicate]如何在一段时间后自动关闭Bootstrap 3模式[重复]
【发布时间】:2014-10-24 00:13:32
【问题描述】:

我正在努力在设定的时间段后自动关闭 Bootstrap 模式。

这是我用来在 4 秒内关闭模式的 js 代码:

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

两个基本问题:

(A) 当 html 页面(包含模态)加载时,模态超时似乎在模态显示之前运行。模式设置为在单击页面中的链接后显示。如果在页面加载时没有立即点击链接,则模式只会短暂出现然后立即关闭,因为基本上超时时间是在加载 html 页面时开始的,而不是在模态已显示。

(B) 如果用户第二次(或第 3 次、第 4 次等)单击链接以启动模态,则模态会正常显示,但 在该时间段后不会关闭。 它会一直保持打开状态,直到用户手动关闭它。

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

(1) 如何让模态超时时间等到模态显示后再运行时钟。

(2) 如何在正确的超时功能仍然有效的情况下让模态显示第二次和第三次?

(以下链接中提出的答案看起来很有希望,但对我不起作用。也许它们不适用于 Bootstrap 3?How to automatically close the bootstrap modal dialog after a minute

下面的代码看起来很有希望,但即使将“显示”更改为“显示.bs.modal”也无法正常工作。还是我把这段代码放错了地方?

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

非常感谢您的任何建议!

【问题讨论】:

  • Bootstrap 3 中的模态事件现在带有后缀,因此您应该使用shown.bs.modal 而不是show,在您链接的答案上也有评论

标签: javascript twitter-bootstrap bootstrap-modal


【解决方案1】:

我不太确定你的 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. 我设置了超时时间 (3000)
  2. 我在里面设置了 myModal 变量 回调

【讨论】:

  • 为我工作谢谢!
【解决方案2】:

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

这里有一个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的信息

我希望这会有所帮助。

【讨论】:

  • 您可以将其用作:setTimeout(function(){$('#myModal').modal('hide')},3000);
猜你喜欢
  • 2021-07-28
  • 1970-01-01
  • 2014-03-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-08
  • 1970-01-01
  • 2019-10-14
  • 1970-01-01
相关资源
最近更新 更多