Javascript 如何使用 Twitter Bootstrap 自动关闭警报

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7643308/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:02:05  来源:igfitidea点击:

How to Automatically Close Alerts using Twitter Bootstrap

javascriptjquerycsstwitter-bootstrapalert

提问by Mario Zigliotto

I'm using twitter's bootstrap CSS framework (which is fantastic). For some messages to users I am displaying them using the alerts Javascript JS and CSS.

我正在使用 twitter 的 bootstrap CSS 框架(这太棒了)。对于给用户的一些消息,我使用警报 Javascript JS 和 CSS 显示它们。

For those interested, it can be found here: http://getbootstrap.com/javascript/#alerts

对于那些感兴趣的人,可以在这里找到:http: //getbootstrap.com/javascript/#alerts

My issue is this; after I've displayed an alert to a user I'd like it to just go away after some time interval. Based on twitter's docs and the code I've looked through it looks like this is not baked in:

我的问题是这样的;在向用户显示警报后,我希望它在一段时间后消失。根据 twitter 的文档和我浏览过的代码,它看起来没有包含在内:

  • My first question is a request for confirmation that this is indeed NOT baked into Bootstrap
  • Secondly, how can I achieve this behavior?
  • 我的第一个问题是要求确认这确实没有融入 Bootstrap
  • 其次,我怎样才能实现这种行为?

回答by jessegavin

Calling window.setTimeout(function, delay)will allow you to accomplish this. Here's an example that will automatically close the alert 2 seconds (or 2000 milliseconds) after it is displayed.

调用window.setTimeout(function, delay)将允许您完成此操作。这是一个示例,它将在显示后 2 秒(或 2000 毫秒)自动关闭警报。

$(".alert-message").alert();
window.setTimeout(function() { $(".alert-message").alert('close'); }, 2000);

If you want to wrap it in a nifty function you could do this.

如果你想把它包装在一个漂亮的函数中,你可以这样做。

function createAutoClosingAlert(selector, delay) {
   var alert = $(selector).alert();
   window.setTimeout(function() { alert.alert('close') }, delay);
}

Then you could use it like so...

然后你可以像这样使用它......

createAutoClosingAlert(".alert-message", 2000);

I am certain there are more elegant ways to accomplish this.

我确信有更优雅的方法来实现这一点。

回答by moogboy

I could not get it to work with alert.('close') either.

我也无法让它与 alert.('close') 一起工作。

However I am using this and it works a treat! The alert will fade away after 5 seconds, and once gone, the content below it will slide up to its natural position.

但是我正在使用它,它很有用!警报将在 5 秒后消失,一旦消失,其下方的内容将向上滑动到其自然位置。

window.setTimeout(function() {
    $(".alert-message").fadeTo(500, 0).slideUp(500, function(){
        $(this).remove(); 
    });
}, 5000);

回答by Mark Daniel

I had this same issue when trying to handle popping alerts and fading them. I searched around various places and found this to be my solution. Adding and removing the 'in' class fixed my issue.

在尝试处理弹出警报和使它们消失时,我遇到了同样的问题。我搜索了各个地方,发现这是我的解决方案。添加和删​​除“in”类解决了我的问题。

window.setTimeout(function() { // hide alert message
    $("#alert_message").removeClass('in'); 

}, 5000);

When using .remove() and similarly the .alert('close') solution I seemed to hit an issue with the alert being removed from the document, so if I wanted to use the same alert div again I was unable to. This solution means the alert is reusable without refreshing the page. (I was using aJax to submit a form and present feedback to the user)

当使用 .remove() 和类似的 .alert('close') 解决方案时,我似乎遇到了从文档中删除警报的问题,所以如果我想再次使用相同的警报 div,我无法做到。此解决方案意味着无需刷新页面即可重复使用警报。(我使用 aJax 提交表单并向用户提供反馈)

    $('#Some_Button_Or_Event_Here').click(function () { // Show alert message
        $('#alert_message').addClass('in'); 
    });

回答by Daniele Armanasco

Using the 'close' action on the alert does not work for me, because it removes the alert from the DOM and I need the alert multiple times (I'm posting data with ajax and I show a message to the user on every post). So I created this function that create the alert every time I need it and then starts a timer to close the created alert. I pass into the function the id of the container to which I want to append the alert, the type of alert ('success', 'danger', etc.) and the message. Here is my code:

对警报使用“关闭”操作对我不起作用,因为它从 DOM 中删除了警报,我需要多次警报(我使用 ajax 发布数据,并在每个帖子上向用户显示一条消息) . 所以我创建了这个函数,每次我需要它时都会创建警报,然后启动一个计时器来关闭创建的警报。我将要附加警报的容器的 ID、警报类型(“成功”、“危险”等)和消息传递给函数。这是我的代码:

function showAlert(containerId, alertType, message) {
    $("#" + containerId).append('<div class="alert alert-' + alertType + '" id="alert' + containerId + '">' + message + '</div>');
    $("#alert" + containerId).alert();
    window.setTimeout(function () { $("#alert" + containerId).alert('close'); }, 2000);
}

回答by Johniboy

This is the coffescript version:

这是 coffescript 版本:

setTimeout ->
 $(".alert-dismissable").fadeTo(500, 0).slideUp(500, -> $(this.remove()))
,5000

回答by biggles

With each of the solutions above I continued to lose re-usability of the alert. My solution was as follows:

对于上述每个解决方案,我继续失去警报的可重用性。我的解决方案如下:

On page load

在页面加载时

$("#success-alert").hide();

Once the alert needed to be displayed

一旦需要显示警报

 $("#success-alert").show();
 window.setTimeout(function () {
     $("#success-alert").slideUp(500, function () {
          $("#success-alert").hide();
      });
 }, 5000);

Note that fadeTo sets the opacity to 0, so the display was none and the opacity was 0 which is why I removed from my solution.

请注意,fadeTo 将不透明度设置为 0,因此显示为无且不透明度为 0,这就是我从解决方案中删除的原因。

回答by leeroya

I needed a very simple solution to hide something after sometime and managed to get this to work:

我需要一个非常简单的解决方案来在一段时间后隐藏一些东西并设法让它工作:

In angular you can do this:

在角度你可以这样做:

$timeout(self.hideError,2000);

Here is the function that i call when the timeout has been reached

这是我在达到超时时调用的函数

 self.hideError = function(){
   self.HasError = false;
   self.ErrorMessage = '';
};

So now my dialog/ui can use those properties to hide elements.

所以现在我的对话框/ui 可以使用这些属性来隐藏元素。

回答by GigolNet Guigolachvili

With delay and fade :

使用延迟和淡入淡出:

setTimeout(function(){
    $(".alert").each(function(index){
        $(this).delay(200*index).fadeTo(1500,0).slideUp(500,function(){
            $(this).remove();
        });
    });
},2000);

回答by danny

try this one

试试这个

$(function () {

 setTimeout(function () {
            if ($(".alert").is(":visible")){
                 //you may add animate.css class for fancy fadeout
                $(".alert").fadeOut("fast");
            }

        }, 3000)

});

回答by isapir

After going over some of the answers here an in another thread, here's what I ended up with:

在另一个线程中浏览了一些答案之后,这就是我的结论:

I created a function named showAlert()that would dynamically add an alert, with an optional typeand closeDealy. So that you can, for example, add an alert of type danger(i.e., Bootstrap's alert-danger) that will close automatically after 5 seconds like so:

我创建了一个名为功能showAlert(),将动态地添加提醒,使用可选的typecloseDealy。例如,您可以添加一个警报类型danger(即 Bootstrap 的警报危险),该警报将在 5 秒后自动关闭,如下所示:

showAlert("Warning message", "danger", 5000);

To achieve that, add the following Javascript function:

为此,请添加以下 Javascript 函数:

function showAlert(message, type, closeDelay) {

    if ($("#alerts-container").length == 0) {
        // alerts-container does not exist, add it
        $("body")
            .append( $('<div id="alerts-container" style="position: fixed;
                width: 50%; left: 25%; top: 10%;">') );
    }

    // default to alert-info; other options include success, warning, danger
    type = type || "info";    

    // create the alert div
    var alert = $('<div class="alert alert-' + type + ' fade in">')
        .append(
            $('<button type="button" class="close" data-dismiss="alert">')
            .append("&times;")
        )
        .append(message);

    // add the alert div to top of alerts-container, use append() to add to bottom
    $("#alerts-container").prepend(alert);

    // if closeDelay was passed - set a timeout to close the alert
    if (closeDelay)
        window.setTimeout(function() { alert.alert("close") }, closeDelay);     
}