javascript onFocus .css 和 onblur .css
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8902808/
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
onFocus .css and onblur .css
提问by henryaaron
My HTML has a placeholder like such:
我的 HTML 有一个这样的占位符:
<input id="additionalsearch" type="text" value="Search Within" onfocus="if (this.value=='Search Within')this.value='';" onblur="if (this.value=='')this.value='Search Within';">
It wasn't my choice and I can't really remove it... but I was wondering how I can set the CSS too... I want to do something like onfocus="if (this.value=='Search Within')this.value=''; $(this).css('color','000000');"
and onblur="if (this.value=='')this.value='Search Within';$(this).css('color', 'A9A9A9');"
. How can I accomplish that?
这不是我的选择,我无法真正删除它...但我想知道如何设置 CSS...我想做类似onfocus="if (this.value=='Search Within')this.value=''; $(this).css('color','000000');"
和的事情onblur="if (this.value=='')this.value='Search Within';$(this).css('color', 'A9A9A9');"
。我怎样才能做到这一点?
Thanks
谢谢
回答by methodofaction
You can use pseudo-selectors:
您可以使用伪选择器:
input[type=text]:focus {
color: black;
}
input[type=text] {
color: gray;
}
回答by Jere
Actually, you pretty much provided the code with the exception of two mistakes:
实际上,您几乎提供了代码,但有两个错误:
- You need a # before your colors.
- You need to wrap your conditionals in braces
- 你的颜色前需要一个#。
- 您需要将条件括在大括号中
Everything else was fine (I changed the colors to make it more obvious what was happening):
其他一切都很好(我改变了颜色以使发生的事情更明显):
<input id="additionalsearch" type="text" value="Search Within" onfocus="if (this.value=='Search Within'){this.value='';$(this).css('color','#00ff00');}" onblur="if (this.value==''){this.value='Search Within';$(this).css('color', '#ff0000');}">
Of course, this ends up being really ugly code and you are advised to put the javascript in separate handlers.
当然,这最终会成为非常丑陋的代码,建议您将 javascript 放在单独的处理程序中。
回答by jcdietrich
You can use the following
您可以使用以下
$('#additionalsearch')
.bind('focus',function(){
if (this.value=='Search Within'){
this.value='';
};
$(this).css('color','black')})
.bind('blur',function(){
if (this.value==''){
this.value='Search Within';
}
$(this).css('color','gray')});
回答by Alexander V. Ulyanov
Tast this:
尝尝这个:
<input id="fldnm" style="background:#B6FF00" type="text" value="Search"
onfocus="if(this.value=='Search'){this.value=''}this.style='background:#FF7F7F';"
onblur="if(this.value==''){this.value='Search'this.style='background:#B6FF00';}else{};"
/>
回答by Ivo
You can use the pseudo-class :focus for the color http://www.w3schools.com/cssref/sel_focus.asp
您可以使用伪类 :focus 作为颜色 http://www.w3schools.com/cssref/sel_focus.asp
As for the "Search Within" thing, I recommend using the defaultText jQuery plug-in
至于“Search Within”的东西,我推荐使用defaultText jQuery插件