2013-03-04 24 views
0

当用户点击它时,我可以使用CSS更改输入字段值吗?是否可以使用CSS更改输入值?

像:

<input type=text name=username> 
<input type=password name=password> 

所以,当用户点击进入该领域,该文本将消失,他就可以写的东西。

我曾尝试:

input[value="Input desired username here"] { 
styles... 
} 

任何线索?

+0

顺便说一句,把你的html属性放在双引号内。 'type = text'必须变成'type =“text”'等等...... – 2013-03-04 22:33:28

+0

[用css更改文本输入值的可能的重复项](http://stackoverflow.com/questions/7672521/change-a -text-inputs-value-with-css) – kittykittybangbang 2015-06-15 17:22:21

回答

4

没有必要为此使用css。您可以使用占位符属性为您输入的标签,它会显示在输入框的默认值:

<input type="text" name="username" placeholder="Username" /> 

请考虑placeholder属性不是所有的浏览器都支持,如果你想让它跨浏览器,你可以编写JavaScript代码放到你的输入框中的默认值或使用这个简单而快速修复:

<input type="text" name="username" onFocus="if(this.value=='Username') this.value='';" onBlur="if(this.value=='') this.value='Username';" value="Username" /> 
+1

Uhhh haaa !!你很酷!非常感谢! – Darkeden 2013-03-04 22:32:09

+0

搜索互联网=浪费一些时间/在stackoverflow上发布问题=浪费几分钟/得到确切的答案= PRICELESS! :) – Darkeden 2013-03-04 22:33:06

+0

欢迎您。您可以将答案标记为已接受! – 2013-03-04 22:34:01

2

这就是所谓的占位符。现代浏览器将允许您使用像这样的占位符属性:

<input type="text" name="username" placeholder="Input desired username here" /> 

它会按您的意愿显示。然后,您需要使用Modernizr来将该功能移回旧版浏览器。类似这样的JavaScript有助于:

$(document).ready(function() { 
    if(!Modernizr.input.placeholder) { 
    $('[placeholder]').focus(function() { 
     var input = $(this); 
     if (input.val() == input.attr('placeholder')) { 
     input.val(''); 
     input.removeClass('placeholder'); 
     } 
    }).blur(function() { 
     var input = $(this); 
     if (input.val() == '' || input.val() == input.attr('placeholder')) { 
     input.addClass('placeholder'); 
     input.val(input.attr('placeholder')); 
    }).blur(); 
    $('[placeholder]').parents('form').submit(function() { 
     $(this).find('[placeholder]').each(function() { 
     var input = $(this); 
     if (input.val() == input.attr('placeholder')) { 
      input.val(''); 
     } 
     }) 
    }); 
    } 
}) 
相关问题