type為text或password的input,其在實際應用時,往往有一個占位符,類似這樣的:
在沒有html5前,一般寫成value,用js實現交互,文本框獲得焦點時,提示文字消失,失去焦點時,文字又出現,這樣體驗很好,而且也不用在文本框前面放上功能字樣的文字了,節省空間。貼一段jquery代碼好了:
$(":input").focus(function(){//默認文字消失
if($(this).val()==this.defaultValue){
$(this).val("");
}
}).blur(function(){//默認文字出現
if($(this).val()==""){
$(this).val(this.defaultValue);
}
});
而在html5中,input文本框或textarea文本域有了自己的占位符屬性,placeholder,替代了value,也不用寫js了,其本身就具備了用戶輸入內容時,提示文字消失的功能。
我的偶象大神張鑫旭很早就寫過一篇文章,詳細闡述其特性,原文地址:http://www.zhangxinxu.com/wordpress/?p=2169
但是呀,令人頭疼的IE,
看看這一片綠海中的幾點紅,ie簡直就是大魔王,而且呢,ie8不兼容就算了,ie9也不兼容,這怎么能放心的使用呢,使用了也會被領導檢出bug的。
還是用回value吧,但是,這么好的屬性不用就是不甘心呢,太太可惜了吧。沒關系,有問題找度娘啊,搜搜搜,讓placeholder能兼容ie的搜索結果不要太多哦。
最后,找到一個最完美的解決辦法,而且兼容password。使用了插件jquery-placeholder.js
用法簡單,只要引入jquery庫文件和插件文件,並添加一行代碼調用即可,具體如下:
<!DOCTYPE html>
<html>
<head>
<title></title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery-placeholder.js"></script>
<script>jQuery(function($){$.placeholder.ini();})</script>
<style>input{width:500px}</style>
</head>
<body>
<div>
<div>
<span>username:</span>
<span>
<input type="text" placeholder="Put your name here, max length is 16 letters" maxlength="16" />
</span>
</div>
<div>
<span>password:</span>
<span>
<input type="password" placeholder="Your password here" />
</span>
</div>
</div>
</body>
</html>