在web开发中,有时需要实时的向用户提示一些有用的信息,比如数据库插入/删除成功,网络情况等。而由于面板上的空间有限,我们需要设置一种可以动态显示的提示信息,这种信息在页面上动态生成,过一段时间(如5秒)后自动消失,这样既可以通知到用户,又可以节省页面上的空间。
事实上,一些桌面应用早就使用了这个技术,比如gmail的提示,卡巴斯基的提示等都采取这种方式。周末研究了一下这块,自己用javascript和CSS实现了一个动态的tip。先看看效果:
提示可以有很多种,每一种都可以定义一个样式。
从上边的分析来看,我们的动态tip需要这样几个参数:
- container:提示消息的容器(用于动态加载消息,并负责呈现)
- type:类型(用于表示消息的类型,如错误,警告,信息,其他)
- text:文字信息(消息体)
- timeout:超时参数(指定该消息在timeout毫秒后自动消失)
下面是这个模块的具体实现:
/* * @param container the container of the tip * @param type the type of the tip [error, warnning, infor, other] * @param text of the tip, could be any thing you want to show to user. * @param timeout when timeout,the tip will disappear * */ function showTip(container, type, text, timeout){ var tipContainer = document.getElementById(container); var tip = document.createElement('div'); var icon = document.createElement('img'); var tipSpan = document.createElement('span'); if(type == 'error'){ tip.setAttribute('class', 'errorTip'); icon.src = 'images/incorrect.gif'; }else if(type == 'warnning'){ tip.setAttribute('class', 'warnningTip'); icon.src = 'images/error.png'; }else if(type == 'infor'){ tip.setAttribute('class', 'inforTip'); icon.src = 'images/infor.gif'; }else{ tip.setAttribute('class', 'otherTip'); icon.src = 'images/correct.gif'; } tipSpan.innerHTML = text; var tab = document.createElement('table'); tab.border = '0px'; var row = tab.insertRow(0); row.insertCell(0).appendChild(icon); row.insertCell(1).appendChild(tipSpan); tip.appendChild(tab); tipContainer.appendChild(tip); // set timeout handler setTimeout(function(){ tipContainer.removeChild(tip); }, timeout); }
下面是我定义的几个简单的样式,可以自己修改:
.errorTip{ padding:2px 3px 3px 8px; border:1px solid #666666; font-size:0.9em; color:#000000; background:#FF0066; } .warnningTip{ padding:2px 3px 3px 8px; border:1px solid #666666; font-size:0.9em; color:#000000; background:#FFEACC; } .inforTip{ padding:2px 3px 3px 8px; border:1px solid #666666; font-size:0.9em; color:#000000; background:#C2CFF1; } .otherTip{ padding:2px 3px 3px 8px; border:1px solid #666666; font-size:0.9em; color:#000000; background:#FFFFFF; }
顺便在这里给Vim做一下宣传,这里使用了一个vim的CSS插件,当定义了颜色值后,vim可以直接在编辑器中显示出这个颜色来,如下图所示:
哈哈,比较神奇吧。好了,我们的动态tip就算介绍完成了。整个流程比较简单,做一下分析:
- 根据传入的container的id找到container
- 新建一个div
- 新建一个img,一个span,分别用于存放icon和text信息
- 新建一个table,并设置其border为0,
- 在table上建一个行,并在行上建两列
- 将img和span分别加载到这两个列上
- 设置timeout处理函数
唯一值得一说的是这个setTimeout函数的使用,这体现了javascipt作为一个牛B语言的牛B之处:
setTimeout(function(){ tipContainer.removeChild(tip); }, timeout);
第一个参数是一个函数,相当于C里的函数指针,第二个参数是一个时间值(毫秒级)。当timeout时,调用第一个函数。在这个例子中,这个函数是一个匿名函数,当然也可以定义在外部。
JavaScript是一个神奇的语言,我们平时在web中只用到了其中的一部分。在以后,我会陆续把我对JavaScript的学习的笔记贴出来,敬请关注。