2014-11-14 127 views
19

我有一個divs列表,並允許我的用戶通過發佈新內容動態地添加一個新的。如果用戶發佈新內容,我想通過將新div的背景顏色淡化爲另一種顏色並將其淡化回來,從而在屏幕上突出顯示它。我很接近:CSS過渡:淡入淡出背景色,重置後

http://jsfiddle.net/pUeue/1953/

我使用這個CSS來觸發轉換:

.backgroundAnimated{ 
    background-color: #AD310B !important; 
    background-image:none !important; 
    -webkit-transition: background-color 5000ms linear; 
    -moz-transition: background-color 5000ms linear; 
    -o-transition: background-color 5000ms linear; 
    -ms-transition: background-color 5000ms linear; 
    transition: background-color 5000ms linear; 
    -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */ 
    animation-direction: alternate; 

    -webkit-animation-iteration-count: 2; /* Chrome, Safari, Opera */ 
    animation-iteration-count: 2; 
} 

我可以淡化其他顏色,但它不會褪色了。我想知道是否有人有建議來完成這個任務?我知道有很多的方法可以做到這一點,但我希望能包含此完全在CSS(除動態添加CSS類,通過jQuery。

感謝您的任何建議...

回答

39

您可以使用動畫關鍵幀。沒有額外的JavaScript需要。

$('input[type=button]').click(function() { 
 
$('#newContent').addClass('backgroundAnimated'); 
 
});
@-o-keyframes fadeIt { 
 
    0% { background-color: #FFFFFF; } 
 
    50% { background-color: #AD301B; } 
 
    100% { background-color: #FFFFFF; } 
 
} 
 
@keyframes fadeIt { 
 
    0% { background-color: #FFFFFF; } 
 
    50% { background-color: #AD301B; } 
 
    100% { background-color: #FFFFFF; } 
 
} 
 

 
.backgroundAnimated{  
 
    background-image:none !important; 
 
     -o-animation: fadeIt 5s ease-in-out; 
 
      animation: fadeIt 5s ease-in-out; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div>Old stuff</div> 
 
<div>Old stuff</div> 
 
<div>Old stuff</div> 
 
<div id="newContent">New stuff, just added</div> 
 

 
<input type="button" value="test" />

+1

啊 - 這很巧妙。我比你更喜歡你的回答;) – cport1 2014-11-14 19:34:18

+0

精美的作品!謝謝! – BenjiFB 2014-11-14 19:43:33

+0

有沒有簡單的方法來再次運行動畫? – althaus 2016-02-25 10:55:01

3

嗯。如果你想保持它在CSS,你可以添加一個setTimeout的點擊事件裏面,然後添加其他類。

$('input[type=button]').click(function() { 
$('#newContent').addClass('backgroundAnimated'); 
    setTimeout(function(){ 
     $('#newContent').addClass('nextBackgroundAnimated'); 
    }, 5000); 
}); 

CSS ::

.backgroundAnimated{ 
     background-color: #AD310B !important; 
     background-image:none !important; 
    -webkit-transition: background-color 5000ms linear; 
    -moz-transition: background-color 5000ms linear; 
    -o-transition: background-color 5000ms linear; 
    -ms-transition: background-color 5000ms linear; 
    transition: background-color 5000ms linear; 
     -webkit-animation-direction: alternate; /* Chrome, Safari, Opera */ 
    animation-direction: alternate; 

     -webkit-animation-iteration-count: 2; /* Chrome, Safari, Opera */ 
    animation-iteration-count: 2; 
} 
.nextBackgroundAnimated{ 
     background-color: white !important; 
     background-image:none !important; 
} 

http://jsfiddle.net/pUeue/1954/

+1

+1你的答案呢,因爲它的工作原理。謝謝! – BenjiFB 2014-11-14 19:44:25