Javascript 更改文本字段中的文本颜色
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2516784/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Change text color in text field
提问by Simon
I have an input text field, which has a value "something" by default, but when I start to type, I want that the default value changes color, and the text i'll type, another one.
我有一个输入文本字段,默认情况下它的值为“某物”,但是当我开始键入时,我希望默认值更改颜色,而我将键入的文本更改为另一个。
How can i do that?
我怎样才能做到这一点?
<input type="text" value="something" onclick="this.value=''" />
回答by Chibu
To keep it simple like your example:
为了像您的示例一样保持简单:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
And that should pretty much do it.
这应该几乎可以做到。
回答by Daniel Vassallo
You may want to try the following:
您可能想尝试以下操作:
<input type="text" value="something"
onFocus="if (this.value == 'something') this.style.color = '#ccc';"
onKeyDown="if (this.value == 'something') {
this.value = ''; this.style.color = '#000'; }">
回答by Levi Hackwith
Going off @chibu's answer, this is how you would do it using jQuery and unobtrusive Javascript
离开@chibu 的回答,这就是你如何使用 jQuery 和不显眼的 Javascript
$(document).ready(
function() {
$("#mytext").bind(
"click",
function() {
$(this).val("");
$(this).css("color", "red");
}
);
}
)
回答by Otroberts
Here we go:
开始了:
<input type="text" value="something" onclick="this.value='';this.style.color='red';" />
Best of luck!
祝你好运!
Keep coding!
继续编码!

