【发布时间】:2018-09-15 10:37:50
【问题描述】:
我在正在开发的网站上遇到了一个小问题,但这让我很头疼。我同时使用 CSS 动画和 JavaScript 媒体查询。断点是 768px,这会触发一个事件,其中第二个 div 被附加到第一个 div 上。每个 div 都包含一个动画元素。问题是当函数触发时附加元素的动画会重新启动(而另一个元素的动画保持稳定)。
我想找到一种方法,使附加元素的动画在每次越过断点时都不会重新启动。我很确定这与附加的孩子“重新出现”在 DOM 中导致动画重新启动的事实有关。 Bur 我不知道如何解决这个问题。每一点帮助将不胜感激。谢谢。
//---Start of Square Color Animation---
function colorSquare1() {
var square1Blue = document.getElementById("square-1");
var square2Red = document.getElementById("square-2");
if (square1Blue.classList.contains("square-animation-blue")) {
document.getElementById("square-1").classList.toggle("square-animation-red");
} else {
document.getElementById("square-1").classList.toggle("square-animation-blue");
}
if (square2Red.classList.contains("square-animation-blue")) {
document.getElementById("square-2").className = "square";
}
}
function colorSquare2() {
var square2Blue = document.getElementById("square-2");
var square1Red = document.getElementById("square-1");
if (square2Blue.classList.contains("square-animation-blue")) {
document.getElementById("square-2").classList.toggle("square-animation-red");
} else {
document.getElementById("square-2").classList.toggle("square-animation-blue");
}
if (square1Red.classList.contains("square-animation-blue")) {
document.getElementById("square-1").className = "square";
}
}
//---End of Square Color Animation---
//---Start of Queries Animation---
function myFunction(x) {
if (x.matches) {
var mainContainer = document.getElementById("container-1");
var square2 = document.getElementById("square-container-2");
mainContainer.appendChild(square2);
} else {
var square2 = document.getElementById("square-container-2");
var secondContainer = document.getElementById("container-2");
secondContainer.appendChild(square2);
}
}
var x = window.matchMedia("(min-width: 768px)")
myFunction(x)
x.addListener(myFunction)
//---End of Queries Animation---
#container {
max-width: 72px;
margin: 0 auto;
}
.square {
width: 54px;
height: 54px;
background-color: red;
display: block;
margin-bottom: 20px;
}
.square-animation-blue {
animation-name: changeToBlue;
animation-duration: 0.5s;
animation-fill-mode: forwards;
}
@keyframes changeToBlue {
from {
background-color: red;
}
to {
background-color: blue;
}
}
.square-animation-red {
animation-name: changeToRed;
animation-duration: 0.5s;
animation-fill-mode: forwards;
}
@keyframes changeToRed {
from {
background-color: blue;
}
to {
background-color: red;
}
}
<div id="container">
<div id="container-1">
<div id="square-container-1">
<a href="#" id="square-1" class="square" onclick="colorSquare1()"></a>
</div>
</div>
<div id="container-2">
<div id="square-container-2">
<a href="#" id="square-2" class="square" onclick="colorSquare2()"></a>
</div>
</div>
</div>
【问题讨论】:
标签: javascript html css media-queries css-animations