这是一款炫酷的jQuery和CSS3表单浮动标签特效。浮动标签是指输入框中的文字或占位文本在输入框聚焦的时候,以动画的方式浮动到指定的地方。浮动标签特效是一种新颖时尚的动画特效,不仅效果很酷,而且能以明确的方式提示用户该输入框应该填写上面内容,用户体验非常不错。
这个浮动标签特效中共有4种不同的动画效果。分别是Fieldset样式的浮动标签,使用font-size来动画的浮动标签,使用CSS3 transforms和jquery easing来动画的浮动标签和透明度动画浮动标签。
使用方法
HTML结构
这4中浮动标签的HTML结构都使用
First Name
CSS样式
每一中浮动标签的CSS样式各不相同,来看看第一种浮动标签的设计方式。第一种浮动标签方式使用的是Fieldset,在输入框聚焦的时候,占位文本会浮动到Filedset上面。为了美观,整个效果还添加了一层包裹元素以及一个h2文本作为大标题。为元素添加一些节本样式:
main {
width: 500px; margin: 0 auto; padding-bottom: 10px;
background: white; border-radius: 3px; overflow: hidden;
}
main h2 {
font-size: 24px; font-weight: normal;
background: hsl(120, 40%, 95%); color: hsl(120, 40%, 40%);
text-align: center;
padding: 20px 0; margin-bottom: 40px;
}
form表单中的div设置为相对定位。div中的input和label元素设置相同的宽度、高度和行高。在高度设置上,为了修补Firefox浏览器的一个小bug,使用一个计算公式来获取高度。height = 24(lineheight) + 10*2(padding) + 2(border)。
.flp input, .flp label {
width: 400px; display: block;
font: inherit; font-size: 16px; line-height: 24px;
/*fixed height for FF line height issue.
height = 24(lineheight) + 10*2(padding) + 2(border)*/
height: 46px;
border: 1px solid #999;
}
然后input和label元素分别设置各自的不同样式,label元素需要动画,设置为绝对定位方式,并且它的左右padding要比上下padding少2个像素,因为后面需要做单个文字的动画,在.ch中会补足这2个像素。
最后是实际的动画效果的CSS样式。插件初始化的时候,会将所有的字母单独使用包裹起来,做成一个一个的单独字母。在输入框聚焦的时候,js代码会为输入框元素添加.focussed class。实际的字母浮动动画是通过jquery.easing来完成的。
/*label styles*/
.ch {
display: block; float: left;
position: relative; /*for upward animation*/
background: white;
}
.ch:first-child {padding-left: 2px;}
.ch:last-child {padding-right: 2px;}
/*active input label*/
.focussed {
/*when any input is already focussed clicking on it(label) again won't do anything*/
pointer-events: none;
}
JAVASCRIPT
该浮动标签效果中使用jquery.easing来完成实际的动画特效。首先,插件在初始化时将每一个输入框中的文字打散为单个的字母,每一个字母都用元素来包裹起来。接下来当输入框聚焦的时候,使用jquery.easing来完成字母的浮动动画特效。
//breakdown the labels into single character spans
$(".flp label").each(function(){
var sop = ''; //span opening
var scl = ''; //span closing
//split the label into single letters and inject span tags around them
$(this).html(sop + $(this).html().split("").join(scl+sop) + scl);
//to prevent space-only spans from collapsing
$(".ch:contains(' ')").html(" ");
})
var d;
//animation time
$(".flp input").focus(function(){
//calculate movement for .ch = half of input height
var tm = $(this).outerHeight()/2 *-1 + "px";
//label = next sibling of input
//to prevent multiple animation trigger by mistake we will use .stop() before animating any character and clear any animation queued by .delay()
$(this).next().addClass("focussed").children().stop(true).each(function(i){
d = i*50;//delay
$(this).delay(d).animate({top: tm}, 200, 'easeOutBack');
})
})
$(".flp input").blur(function(){
//animate the label down if content of the input is empty
if($(this).val() == "")
{
$(this).next().removeClass("focussed").children().stop(true).each(function(i){
d = i*50;
$(this).delay(d).animate({top: 0}, 500, 'easeInOutBack');
})
}
})
其它几个效果的CSS和JS都分别写在了HTML文件中,原理基本相同,你可以下载来自行研究。