2016-02-13 97 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