如何过渡具有延迟效果的不同背景颜色

How to transition different background colors with a delay effect

本文关键字:背景 颜色 何过渡 延迟      更新时间:2023-09-26

我正在创建一系列过渡/动画,因此对于这个特定示例,我需要有一个javascript解决方案,而不是css关键帧解决方案。

我正在为我的许多不同的序列使用延迟,并且我正在尝试使用新的背景颜色做同样的事情,但由于某种原因,使用 addClass 函数对我不起作用。

为什么这对我不起作用?

//$(".blue").delay(2500).addClass("green-fill");
$(".green-fill").delay(2500).addClass("green-fill");
.blue {
	background-color: #0085A1;
	width: 100%;
	height: 100vh;
	position: relative;
	text-align: center;
}
.green-fill {
	display: none;
	background: green;
	width: 100%;
	height: 100vh;
	position: relative;
	text-align: center;
	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
	</div>
</div>

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); 

您正在尝试将类"绿色填充"添加到完全相同的类"绿色填充"中。因此,该类将立即应用于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 可以保持不变。