表單提示就是在input輸入框予以文字提示,當內容改變時提示文字消失的效果。實現方法有很多種,HTML5的placeholder也能方便的實現,下面簡單介紹下
1.placeholder解決方案
百科:placeholder是html5中的表單佔位符,支持text,password及textarea等html5中新增的表單元素。
效果:
方法:
<input id="name" type="text" placeholder="please enter the text" />
1 |
<input id="name" type="text" placeholder="please enter the text" /> |
2.placeholder兼容
既然是html5,那麼當然只有高級瀏覽器可以支持了(所以使用低級瀏覽器的同學在上一個例子是看不到效果的),不過我們可以借用jquery來幫我們來解決這個兼容問題。
jQuery代碼(記得先引入jQuery庫),然後再引入placeholder.js(點擊下載)
$(function() { $('input, textarea').placeholder(); });
1 2 3 |
$(function() { $('input, textarea').placeholder(); }); |
關於placeholder文字的顏色
火狐和webkit內核瀏覽器可以直接通過css來控制,分別爲:-moz-placeholder和::-webkit-input- placeholder,調用這個js後,會給不支持placeholder的加上placeholder這個class,所以整合起來是:
css代碼
:-moz-placeholder, ::-webkit-input-placeholder{ color: #bfbfbf; } .placeholder{ color: #bfbfbf; }
1 2 3 4 5 6 7 |
:-moz-placeholder, ::-webkit-input-placeholder{ color: #bfbfbf; } .placeholder{ color: #bfbfbf; } |
注:請注意不要把這兩個樣式寫在一起,如果集體聲明ie8,9將不能正確解析.placeholder的樣式。
3.javascript解決方案
<input type="text" value="請輸入關鍵詞" onFocus="if(value==defaultValue){value='';this.style.color='#000'}" onBlur="if(!value){value=defaultValue;this.style.color='#bfbfbf'}" style="color:#bfbfbf" />
1 2 3 4 |
<input type="text" value="請輸入關鍵詞" onFocus="if(value==defaultValue){value='';this.style.color='#000'}" onBlur="if(!value){value=defaultValue;this.style.color='#bfbfbf'}" style="color:#bfbfbf" /> |
4.jQuery解決方案
$("input,textarea").css({color:"#bfbfbf"}); $(":input").focus(function(){ $(this).css({color:"#000"}); if($(this).val() ==this.defaultValue){ $(this).val(""); } }).blur(function(){ if ($(this).val() == '') { $(this).val(this.defaultValue); $(this).css({color:"#bfbfbf"}); } });
1 2 3 4 5 6 7 8 9 10 11 12 |
$("input,textarea").css({color:"#bfbfbf"}); $(":input").focus(function(){ $(this).css({color:"#000"}); if($(this).val() ==this.defaultValue){ $(this).val(""); } }).blur(function(){ if ($(this).val() == '') { $(this).val(this.defaultValue); $(this).css({color:"#bfbfbf"}); } }); |