KingBow

简单,美好,奋发


走在前端进阶之路


复活弹出提示框

目录:
1、HTML代码
2、CSS代码
3、Javascript代码

在表单提交中,不论成功与否,好的体验都应该有弹出提示,效果:

(https://img-blog.csdnimg.cn/20190620172120518.png) 在页面中央显示提示,1.5秒后消失,不影响页面的正常布局。

1 HTML代码

HTML代码显示提示内容,放在页面中任何位置。

1
<div class="alert"></div>

2 CSS代码

弹出框参考了 Bootstrap 的样式:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
.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;
}

3 JavaScript代码

首先,加载JQuery,然后用下面代码实现1.5秒后淡出效果:
1
$('.alert').html('操作成功').addClass('alert-success').show().delay(1500).fadeOut();

还可结合关闭窗口代码:

1
2
3
4
5
6
//关闭网页
window.opener = null;
window.open('', '_self');
window.close();
//关闭微信网页
setTimeout("WeixinJSBridge.call('closeWindow')", 1000);

如果不想在HTML中加DIV,可以直接用JS把DIV添加到页面中,如下:
$('<div>').appendTo('body').addClass('alert alert-success').html('操作成功').show().delay(1500).fadeOut(); 一般情况下,如果这个方式使用得很频繁,写成函数可以提高复用:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
* 弹出式提示框,默认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);
};

这样比用setTimeout()结构更清晰。