CSS或JS-当输入被聚焦时,改变输入的背景颜色

CSS or JS - change background color of input when input is focused out?

本文关键字:输入 改变 颜色 背景 聚焦 JS- CSS      更新时间:2023-09-26

当输入文本失去焦点时,有什么方法可以在输入文本上设置background-color吗?

我正在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');
      }
      });

感谢

CSS3方法可以是,例如:

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

请参阅此FIDDLE。它有点向后,你可以设置活动选择器的样式,而不是模糊选择器的样式。

要模拟模糊,可以使用:not(:focus),请参见此处

文本区域和输入是不同的选择器:

使用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; }