onFocus .css and onblur .css

onFocus .css and onblur .css

本文关键字:css onblur and onFocus      更新时间:2023-09-26

我的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';">

这不是我的选择,我真的不能删除它…但我想知道如何设置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');"的事情。我怎样才能做到这一点?

感谢

您可以使用伪选择器:

input[type=text]:focus {
  color: black;
}
input[type=text] {
  color: gray;
}

实际上,除了两个错误之外,您几乎提供了代码:

  1. 你需要在你的颜色之前加一个#
  2. 你需要用大括号括条件句

其他一切都很好(我改变了颜色,让发生的事情更加明显):

<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');}">

http://jsfiddle.net/A4cuy/6/

当然,这最终会变成非常难看的代码,建议您将javascript放在单独的处理程序中。

您可以使用pseudo-class:focus作为颜色http://www.w3schools.com/cssref/sel_focus.asp

至于"Search Within",我建议使用defaultText jQuery插件

http://archive.plugins.jquery.com/project/defaultInputText

您可以使用以下

$('#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')});

品尝这个:

<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{};"
   />