如何在几秒钟内更改聚焦元素的背景颜色?

时间:2016-01-30 11:07:42

标签: javascript jquery html css

这里的代码重点放在第二个div上。现在我想将聚焦元素的背景颜色设置为另一种颜色几秒钟,然后淡化回原始颜色。怎么做?

$(function(){
    $("#two").focus();
});
body{color:white;}
#fis{height:600px;width: 60px;background-color:red;}
#two{height:600px;width: 60px;background-color:green;}
#thr{height:600px;width: 60px;background-color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fis">hello
</div>
<div id='two' tabindex='1'>mr
</div>
<div id='thr'>john
</div>

3 个答案:

答案 0 :(得分:4)

以下是在setTimeout事件中使用focus的解决方案。

$(function(){
    $('div').on('focus', function() {
       var $this = $(this);
       $this.addClass('highlight');
       setTimeout(function(){
         $this.removeClass('highlight');
       }, 2000);
    })
    $("#two").focus();
});
body{color:white;}
#fis{height:600px;width: 60px;background-color:red;}
#two{height:600px;width: 60px;background-color:green;}
#thr{height:600px;width: 60px;background-color:blue;}
#fis.highlight{background-color:yellow;}
#two.highlight{background-color:yellow;}
#thr.highlight{background-color:yellow;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fis">hello
</div>
<div id='two' tabindex='1'>mr
</div>
<div id='thr'>john
</div>

答案 1 :(得分:2)

以下方式您可以在一段时间内更改颜色。首先它会在几秒后变黄然后变回绿色。

$(function(){
  
   $("#two").focus();
  
   setTimeout(function() {
        $('#two').css("background-color", "green");
    }, 2000);
  
});
body{color:white;}
#fis{height:600px;width: 60px;background-color:red;}
#two{height:600px;width: 60px;background-color:yellow; transition:background-color 1s ease;}
#thr{height:600px;width: 60px;background-color:blue;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fis">hello
</div>
<div id='two' tabindex='1'>mr
</div>
<div id='thr'>john
</div>

答案 2 :(得分:2)

$(document).ready(function(){
    $("#two").focus(function(){
        $(this).css("background-color","green");
         setTimeout(function(){

             $("#two").css("background-color","yellow");
        },1000);
    });    
});

试试这个......

相关问题