表单提示就是在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"});

       }

     });