這是一款炫酷的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文件中,原理基本相同,你可以下載來自行研究。