Проблемы с медиа-запросами JavaScript и анимацией CSS - PullRequest
0 голосов
/ 14 сентября 2018

Я обнаружил небольшую проблему на веб-сайте, над которым я работаю, но это ломает мне голову. Я использую CSS-анимацию и JavaScript медиа-запросы одновременно. Точка разрыва составляет 768 пикселей, и это вызывает событие, при котором второй div добавляется к первому. Каждый div содержит анимированный элемент. Проблема заключается в том, что анимация добавленного элемента перезагружается при срабатывании функции (пока анимация другого элемента остается стабильной).

Я хотел бы найти способ, при котором анимация добавленного элемента не перезагружается каждый раз, когда вы пересекаете точку останова. Я почти уверен, что это связано с тем фактом, что добавленные дочерние элементы «появляются» в DOM, вызывая перезагрузку анимации. Но я не знаю, как это исправить. Каждая помощь будет высоко ценится. Спасибо.

//---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>

1 Ответ

0 голосов
/ 15 сентября 2018

Вместо использования анимации вы можете использовать CSS-свойство перехода.

.square-animation-blue{
    transition: background-color 0.5s;
    background-color: blue;
}

CSS-переходы: https://www.w3schools.com/css/css3_transitions.asp

<!DOCTYPE html>
 <html>
 <head>
  <meta charset="UTF-8">
  <meta http-equiv='X-UA-Compatible' content='IE=edge'>
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <style type="text/css">
    #container{
        max-width: 72px;
        margin: 0 auto;
    }
    .square{
        width: 54px;
        height: 54px;
        background-color: red;
        display: block;
        margin-bottom: 20px;
    }
    .square-animation-blue{
        transition: background-color 0.5s;
        background-color: blue;
    }
    
    .square-animation-red{
        transition: background-color 0.5s;
        background-color: red;
    }
    


</style>
</head>
<body>
 <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>
    <script>
    	//---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) {
        	console.log("moved to container 1");	
            var mainContainer = document.getElementById("container-1");
            var square2 = document.getElementById("square-container-2");

            mainContainer.appendChild(square2);

        } else {
            console.log("moved to container 2");	
            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---    
    </script>
  </div>
</body>
</html>
...