html - CSS:在另一个动画期间更改div的颜色
问题描述
我想在另一个 div 执行动画时更改 div 的颜色。我已经准备好我的 html 文件:
.body {
width: 1200px;
background-color: white;
font-family: sans-serif;
font-size: 20px;
margin: 50px;
}
.bar {
stroke: black;
stroke-width: 0.1;
background-color: cornflowerblue;
width: 500px;
height: 25px;
left: 100px;
top: 100px;
position: absolute;
animation-name: expandBar;
animation-duration: 2s;
animation-delay: 1s;
animation-fill-mode: both;
transition-timing-function: ease-in-out;
}
@keyframes expandBar {
from {
width: 0px;
}
to {
width: width;
}
}
.box {
stroke: black;
stroke-width: 0.1;
background-color: cornflowerblue;
width: 100px;
height: 100px;
left: 100px;
top: 135px;
position: absolute;
}
<html lang="de">
<head>
<meta charset="utf-8" />
<title>Title</title>
<link rel="stylesheet" href="bc.css" />
</head>
<body>
<div class="bar"></div>
<div class="box"></div>
</body>
</html>
对于初学者,我尝试使用以下代码来测试它是如何工作的(我在互联网上看到过)。工作正常。
.bar:hover ~ .box{
background-color: red;
}
但是,我现在不知道如何处理 bar 元素的动画。我希望在条形图展开的 2 秒内该框为红色。
有没有可以用来代替悬停的关键字?还是有其他方法可以做到这一点?
解决方案
我不能直接想到只使用 CSS 的解决方案。但是一点 javascript 可能会有所帮助。有onanimationstart
,onanimationend
这可能会帮助你。链接到 MDN 文档
下面是一个工作示例。
let bar = document.getElementById("bar")
let box = document.getElementById("box")
bar.onanimationstart = function(event){
box.classList.add("red")
}
bar.onanimationend = function(event){
box.classList.remove("red")
}
#body {
width: 1200px;
background-color: white;
font-family: sans-serif;
font-size: 20px;
margin: 50px;
}
#bar {
stroke: black;
stroke-width: 0.1;
background-color: cornflowerblue;
width: 500px;
height: 25px;
left: 100px;
top: 100px;
position: absolute;
animation-name: expandBar;
animation-duration: 2s;
animation-delay: 1s;
animation-fill-mode: both;
transition-timing-function: ease-in-out;
}
@keyframes expandBar {
from {
width: 0px;
}
to {
width: width;
}
}
#box {
stroke: black;
stroke-width: 0.1;
background-color: cornflowerblue;
width: 100px;
height: 100px;
left: 100px;
top: 135px;
position: absolute;
}
.red{
background-color: red !important;
}
<!DOCTYPE html>
<html lang="de">
<head>
<meta charset="utf-8" />
<title>Title</title>
<link rel="stylesheet" href="bc.css" />
</head>
<body>
<div id="bar"></div>
<div id="box"></div>
</body>
</html>
推荐阅读
- go - 为什么当 annoymouse 函数返回时 defer 语句的工作方式不同
- python - Python - 为绘图构建数据框
- google-cloud-platform - 双引号字符串数据在谷歌存储上以三引号显示
- java - 如何在 5 小时后强制会话退出 TOMCAT 服务器(不是非活动会话退出)
- python - 无法注册碰撞
- firebase - 如何在 Firebase 上创建 Busuu 每日提醒通知
- aws-lambda - 功能即服务 (FaaS) 托管如何在后台工作?
- go - 为什么 go-jaeger-client 需要度量和日志的包装器?
- reactjs - 为什么 Scrollspy 未在反应应用程序中加载?
- java - 异步回调和监听器