代码之家  ›  专栏  ›  技术社区  ›  at.

显示指令(占位符)文本的Javascript文本输入字段

  •  10
  • at.  · 技术社区  · 14 年前

    最好的方法是让文本输入字段以灰色显示输入内容的说明。当您聚焦于该输入字段时,灰色的指令文本将消失,而您的输入文本将显示为黑色。如果删除输入文本并将焦点从该输入上移开,则指令灰色文本将重新出现。

    我试过用jQuery实现这个功能,但是我在不同的浏览器中遇到了各种奇怪的问题。有时当你回到屏幕上时,指令文本会变成黑色,不再消失,类似这样的问题。

    有标准的javascript库吗?我找不到了!

    7 回复  |  直到 13 年前
        1
  •  7
  •   Haim Evgi    14 年前

    this

    例子

     $(this).Watermark("your instructions");
    
        2
  •  21
  •   autonomatt    13 年前

    你不需要javascript。

    <input type="text" id="email" name="email" placeholder="Enter your email address">
    

    这适用于现代浏览器。如果你加上modernizr.js 你的网页,然后它将在所有浏览器工作。

        3
  •  2
  •   Reigel Gallarde    14 年前

    <input type="text" id="user" class="textbox default" value="Enter login name">
    <input type="password" id="pass" class="textbox">
    

    jQuery查询

    $(function(){
      $('.textbox').focus(function(){
        if (this.value == this.defaultValue) {
            this.value = '';
            $(this).removeClass('default');
        };
      }).blur(function(){
        if (this.value == '') {
            this.value = this.defaultValue;
            $(this).addClass('default');
        };
      });​
    });
    

    demo

        4
  •  0
  •   Quentin    14 年前

    例如: http://dorward.me.uk/tmp/label-work/example.html (您只需使用不同的前景色设置标签和输入的样式)

        5
  •  0
  •   Moin Zaman    14 年前
        6
  •  0
  •   ShivarajRH    12 年前

    变量名为,

    var name=$("#con-name");
    var nameval="Enter your name";
    
    
    
    name.val(nameval);
    name.focus(function(){  
         if (this.value == nameval ) { 
             this.value = ''; 
         }; 
        }).blur(function(){ 
             if (this.value == '') {    
             this.value = nameval;  
        };  
     });
     //submit to clear code
     $("#sub_con_page").click(function() {  
        if(name.val()==nameval) { 
           name.val(""); 
         } 
     });
    

    DEMO LINK

        7
  •  -2
  •   PPShein    14 年前
    <input type="text" name="myText" value="Enter Name" style="color:gray" onfocus="this.value=''">