2013-11-25 47 views
4

有什么办法可以在输入文字失焦时设置background-colorCSS或JS - 当输入被聚焦时改变输入的背景颜色?

我想在JS中,但我想知道是否可能在CSS纯。

这似乎不工作

input{ 
background-color:#fff !important; 
} 
input:focus{ 
background-color:#333 !important; 
} 
//input:unfocused and has value{ ??? :) } 

$('input,textarea').on('focusout',function(e){ 
     if($(this).val().length){ 
     $(this).css('background-color','#fff'); 
     } 
     }); 

谢谢

+1

CSS'!important'语句不被jquery'.css()'met支持hod,删除它或使用类 –

+0

@ A.Wolff谢谢你的男人,但仍然不工作,因为我已经在默认情况下background-color:fff重要;在输入时,只是尝试改变背景,如果输入有价值,并专注 – sbaaaang

+0

':焦点'伪类将允许你做它的负面过程。重点时重新着色,然后恢复正常。 – DevlshOne

回答

3

CSS3的方法是,例如:

THIS FIDDLE。它有点落后,你会选择主动,而不是模糊的选择器。

为了模拟模糊,你可以使用:not(:focus)see here

+0

这是为了重点我需要聚焦:P – sbaaaang

+0

@sbaaaang,焦点是相反的。风格正常(非:焦点)选择器为focusout。它相同,但倒过来在CSS – SW4

+0

我需要3 stetements backgrond:输入,输入:焦点,输入:focusout – sbaaaang

1

textarea的输入有不同的选择:

使用jQuery这样做:

<script type="text/javascript"> 
$(document).ready(function(){ 
     $('textarea').on('focusout',function(){ // When losing focus 
      $(this).css('background','#FFF'); 
     }); 
     $('textarea').on('focus',function(){ // When focus 
      $(this).css('background','#333'); 
     }); 
}); 
</script> 

或CSS:

textarea { background-color:#fff !important; } 
textarea:focus { background-color:#333 !important; } 
+0

嘿对不起,我得到的修复它是删除一些CSS现在它的工作该死的对不起,谢谢你的时间,我投了去关闭这个 – sbaaaang