您的位置:首页 > 其它

制作常见的消息提示框

2018-01-24 23:57 169 查看
该控件的效果是从页面右上方徐徐显示出一个消息框,如下图所示。



然后暂时停留若干时间,完毕后自动收缩。在线演示地址:https://framework.ajaxjs.com/framework/ui_demo/form/msg.jsp

首先,了解 HTML 结构如下:

<div class="topMsg">暮從碧山下,山月随人歸。卻顧所來徑,蒼蒼橫翠微。相攜及田家,童稚開荊扉。綠竹入幽徑,青蘿拂行衣。</div>
<button onclick="show();return false;">show</button>
<button onclick="show('保存成功!');return false;">show with text</button>


按钮点击之后就执行 show() 方法显示消息框。show() 是一个只有 11 行的 js 函数:

function show(text, showTime){
var el = document.querySelector('.topMsg');
if(text)
el.innerHTML = text;
el.classList.remove('fadeOut');
el.classList.add('fadeIn');

setTimeout(function(){
el.classList.remove('fadeIn');
el.classList.add('fadeOut');
}, showTime || 3000)
}


可见,该函数非常简单,只是设置一下要显示的文字,和修改相关样式。样式是重头戏,动画效果都是 CSS 来完成。由于笔者习惯 LESS,故 CSS 乃 LESS 写就。

// 首先定义关键帧动画,一个显示、一个隐藏的
@keyframes topMsg-fade-in {
0% {
opacity: 0;
}
30% {
opacity: .2;
}
80% {
opacity: .4;
}
100% {
opacity: 1;
}
}
@keyframes topMsg-fade-out {
0% {
}
30% {
opacity: .2;
}
80% {
opacity: .4;
}
100% {
opacity: 0;
}
}

// 元素样式,采用绝对布局
.topMsg{
position:fixed;
width:300px;
height:80px;
right: 30px;
padding:10px;
border-radius:5px;
color: #0066cc;
box-sizing: border-box;
background-color: #f5faff;
border:1px solid #0066cc;
top: -100px;
transition: top ease-in 550ms;
animation-fill-mode: forwards;
&.fadeIn{
top: 100px;
animation: topMsg-fade-in ease-in 550ms;
}
&.fadeOut{
animation: topMsg-fade-out ease-out 550ms;
}
}


注意 &.fadeIn 表示一个元素同时拥有这两个样式,等于 .topMsg.fadeIn 的 CSS 写法(中间没有空格);若 HTML 表示的话便是

<div class="topMsg fadeIn">


fadeIn 对应显示时的样式,反之 fadeOut 则是消退时候的样式。

样式写的也非常简单,如果大家不太了解个别样式含义百度即可。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: