我有以下标记:
<div class="container">
<div class="content">
...
<div class="no-animate">
...
</div>
</div>
</div>
所以我想对 .container
应用 CSS 动画,但排除其中的 .no-animate
。请注意,.no-animate
具有 position: fixed
属性,这就是我要排除它的原因。
我尝试了以下方法:
@keyframes my-animation {
12.5% {
transform: translateX(-0.5rem);
}
37.5% {
transform: translateX(0.5rem);
}
62.5% {
transform: translateX(-0.2rem);
}
87.5% {
transform: translateX(0.2rem);
}
}
.container {
animation: my-animation 0.5s;
animation-timing-function: linear;
}
.container .no-animate {
animation: none;
}
不幸的是,这似乎没有任何效果,而且 .no-animate
由于动画而移动。非常感谢任何帮助。
答案 0 :(得分:2)
您不能从动画中排除子元素。相反,您可以将该子元素放置在父块之外,但是,您可以应用 position: absolute;
属性来创建一个背景(父)动画的视图,但子元素保持静止。只有解决方法可以做到这一点。我上面提到的其中之一。
答案 1 :(得分:1)
只需应用相同的变换值,但方向相反,以抵消父容器的平移效果。
* {
margin: 0px;
padding: 0px;
}
body {
display: grid;
justify-content: center;
align-items: center;
grid-template-columns: auto auto;
height: 100vh;
}
.container {
height: 500px;
width: 600px;
background: black;
margin: 10px;
animation: move_box 1s linear infinite;
}
@keyframes move_box {
12.5% {
transform: translateX(-0.5rem);
}
37.5% {
transform: translateX(0.5rem);
}
62.5% {
transform: translateX(-0.2rem);
}
87.5% {
transform: translateX(0.2rem);
}
}
.box,
.box_without {
height: 100px;
width: 100px;
background: red;
animation: anti_move_box 1s linear infinite;
}
.box_without {
animation: none;
}
@keyframes anti_move_box {
12.5% {
transform: translateX(0.5rem);
}
37.5% {
transform: translateX(-0.5rem);
}
62.5% {
transform: translateX(0.2rem);
}
87.5% {
transform: translateX(-0.2rem);
}
}
<h1>Red box not moving alongside black box</h1>
<h1>Red box moving alongside black box</h1>
<div class="container">
<div class="box"></div>
</div>
<div class="container">
<div class="box_without"></div>
</div>