2016-02-13 50 views
0

我正在創建一個過渡/動畫序列,所以爲此我需要一個javascript解決方案,而不是一個css關鍵幀解決方案。如何過渡不同的背景顏色,延遲效果

我對很多不同的序列使用了延遲,我試圖用新的背景顏色來做同樣的事情,但由於某種原因,使用addClass函數不適用於我。

爲什麼這不適合我?

//$(".blue").delay(2500).addClass("green-fill"); 
 
$(".green-fill").delay(2500).addClass("green-fill");
.blue { 
 
\t background-color: #0085A1; 
 
\t width: 100%; 
 
\t height: 100vh; 
 
\t position: relative; 
 
\t text-align: center; 
 
} 
 
.green-fill { 
 
\t display: none; 
 
\t background: green; 
 
\t width: 100%; 
 
\t height: 100vh; 
 
\t position: relative; 
 
\t text-align: center; 
 
\t z-index: 1; 
 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
 
<div class="blue"> 
 
    <div class="green-fill"> 
 
    Hello 
 
\t </div> 
 
</div>

+0

您要添加的綠色填充類到已有的一個元素。這顯然是不正確的。 –

+0

那麼,如果我這樣做... https://jsfiddle.net/#&togetherjs=vUJEKQ2BAM ...它仍然沒有做任何事情。 – Paul

回答

1

CSS

.green-fill { 
    background: green; 
    width: 100%; 
    height: 100vh; 
    position: relative; 
    text-align: center; 
    z-index: 1; 

    transition:background-color 1s; 
} 
.green-fill.blue{ 
    background-color:#00f; 
} 

jQuery的

setTimeout(function(){ 
    $(".green-fill").addClass("blue"); 
},2500); 

// That's why css keyframes are better... 
// For smooth ease back : the trick is to copy the color being rendered, then remove class, and then finally remove the inline generated code. 

setTimeout(function(){ 
    var $gb = $(".green-fill"); 
    var color = $gb.css("background-color"); 
    $gb.css("background-color",color).removeClass("blue").css("background-color",""); 

    },5000); 
+0

這會做什麼? '.green-fill.blue {' – Paul

+0

@Paul如果你沒有.blue類已經定義了你想要轉換的新顏色。 .green-fill.blue將優先考慮.blue類中的顏色。所以每當有綠色填充元素的藍色課程,它會優先考慮藍色。 – Sandeep

+0

沒有幫助。我只是想讓綠色背景延遲一段時間,然後在藍色上顯示出來。 – Paul

0

您正試圖將一流的「綠色填充」添加到完全相同的一流的「綠色填充」。所以這個類被直接應用於div。將類更改爲其他內容或給它一個id(就像我在下面的例子中所做的那樣)。

的Javascript:

//$(".blue").delay(2500).addClass("green-fill"); 
$("#fill-it").delay(2500).addClass("green-fill"); 

標記:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> 
<div class="blue"> 
    <div id="fill-it"> 
    Hello 
    </div> 
</div> 

CSS可以保持不變。

+0

謝謝你指點我正確的方向,但它仍然無法正常工作。 – Paul

+0

您是否將JS函數包裝在事件處理程序中,以便它被觸發?嘗試用'$(document).ready(function(){....})來包裝它' – turboLoop

+0

是的。它只是不起作用。不知道爲什麼。 – Paul