2016-01-30 16 views
5

Ở đây mã sẽ tập trung vào div thứ hai. Bây giờ tôi muốn thiết lập màu nền cho phần tử lấy nét thành màu khác trong vài giây và sau đó mờ dần về màu gốc của nó. Làm thế nào để làm điều đó?Làm cách nào để thay đổi màu nền của phần tử lấy nét trong vài giây?

$(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>

Trả lời

2

Tiếp theo cách bạn có thể thay đổi màu sắc cho một số khoảng thời gian. Đầu tiên nó sẽ vàng sau vài giây nó trở lại màu xanh lá cây.

$(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>

4

Đây là giải pháp sử dụng setTimeout trên focus sự kiện.

$(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>

+0

nhờ nhưng tôi nghĩ rằng u bỏ lỡ một cái gì đó không có sự thay đổi màu sắc trong đoạn –

+0

tab 'mr' được đánh dấu (màu vàng) tại bắt đầu và sau 2 giây trở thành màu xanh lá cây, phải không? –

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

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

thử này ...

+1

Vui lòng cung cấp giải thích về cách mã này giải quyết câu hỏi. Điều này sẽ giúp OP hiểu câu trả lời của bạn tốt hơn và giúp người tìm kiếm trong tương lai. – SnareChops

Các vấn đề liên quan