jquery 彈窗信息顯示幾秒後自動消失

CSS 樣式:
alert {
    display: none;
    position: fixed;
    top: 50%;
    left: 50%;
    min-width: 300px;
    max-width: 600px;
    transform: translate(-50%,-50%);
    z-index: 99999;
    text-align: center;
    padding: 15px;
    border-radius: 3px;
}

.alert-success {
    color: #3c763d;
    background-color: #dff0d8;
    border-color: #d6e9c6;
}

.alert-info {
    color: #31708f;
    background-color: #d9edf7;
    border-color: #bce8f1;
}

.alert-warning {
    color: #8a6d3b;
    background-color: #fcf8e3;
    border-color: #faebcc;
}

.alert-danger {
    color: #a94442;
    background-color: #f2dede;
    border-color: #ebccd1;
}

首先,加載JQuery,然後用下面代碼實現1.5秒後淡出效果:

$('.alert').html('操作成功').addClass('alert-success').show().delay(1500).fadeOut();

 

如果不想在HTML中加DIV,可以直接用JS把DIV添加到頁面中,如下:

$('<div>').appendTo('body').addClass('alert alert-success').html('操作成功').show().delay(1500).fadeOut();

 

一般情況下,如果這個方式使用得很頻繁,寫成函數可以提高複用:

/**
 * 彈出式提示框,默認1.2秒自動消失
 * @param message 提示信息
 * @param style 提示樣式,有alert-success、alert-danger、alert-warning、alert-info
 * @param time 消失時間
 */
var prompt = function (message, style, time)
{
    style = (style === undefined) ? 'alert-success' : style;
    time = (time === undefined) ? 1200 : time;
    $('<div>')
        .appendTo('body')
        .addClass('alert ' + style)
        .html(message)
        .show()
        .delay(time)
        .fadeOut();
};

// 成功提示
var success_prompt = function(message, time)
{
    prompt(message, 'alert-success', time);
};

// 失敗提示
var fail_prompt = function(message, time)
{
    prompt(message, 'alert-danger', time);
};

// 提醒
var warning_prompt = function(message, time)
{
    prompt(message, 'alert-warning', time);
};

// 信息提示
var info_prompt = function(message, time)
{
    prompt(message, 'alert-info', time);
};

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章