2

При клике на кнопку кнопка опускаеться вниз и назад. Помогите сделать так чтоб при следуйщем клике она снову виполняла анимацию.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test Anim</title>
  <link rel="stylesheet" href="style.css">
</head>
<body>
  
  <div class="container">
    <button>Stick</button>
  </div>

  <script src="app.js"></script>
</body>
</html>


body {
  background-color: grey;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.container button {
  width: 100px;
  height: 100px;  
}

@keyframes btn {
  0% {
    margin-top: 50px;
  }
  50% {
    margin-top: 60px;
  }
  100% {
    margin-top: 0;
  }
}

button.on {
  animation: btn 900ms linear ;
}



let btn = document.querySelector("button")

btn.addEventListener("click", function () {
  if (!btn.classList.contains("on")) {
    btn.classList.add("on")
  }
  else {
    btn.classList.remove("on")
  }
})

2 ответа 2

1

У вас она не продолжается при втором клике, потому что вы не убираете класс .on после анимации, он убирается у вас при втором событии клика, поэтому каждый четный клик будет просто убирать класс.

Вместо этого вы можете добавить таймер на удаления класса, что гарантирует, что до окончания 900 мс, анимация заново не начнётся.

let btn = document.querySelector("button")

btn.addEventListener("click", function () {
  if (!btn.classList.contains("on")) {
    btn.classList.add("on")
    setTimeout(function(){ 
      btn.classList.remove("on")
    }, 900)
    
  }
})
body {
  background-color: grey;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.container button {
  width: 100px;
  height: 100px;  
}

@keyframes btn {
  0% {
    margin-top: 50px;
  }
  50% {
    margin-top: 60px;
  }
  100% {
    margin-top: 0;
  }
}

button.on {
  animation: btn 900ms linear ;
}
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Test Anim</title>
</head>
<body>
  
  <div class="container">
    <button>Stick</button>
  </div>

</body>
</html>

2
  • 1
    animationend лаконичнее, если к примеру добавить ещё какую то анимашку то времени не хватит и пользователь не увидит весь эффект который хотел показать фронтэнд 6 авг 2021 в 0:51
  • @MaximLensky буду знать, большое спасибо :3 6 авг 2021 в 5:41
1

Проблема в том, что время анимации сейчас указывается в CSS и отловить его сложно (во всяком случае я не знаю как). Поэтому тут предлагаю одно костыльное решение и одно предложение:

  1. Костыльное решение заключается в удалении класса спустя столько же времени, сколько она длится. Минус очевиден: если захочется изменить время - надо менять и там и там. Да и сложно это отследить

let btn = document.querySelector("button")

btn.addEventListener("click", function () {
  if (!btn.classList.contains("on")) {
    btn.classList.add("on");
    setTimeout(() => {  btn.classList.remove("on");  }, 900);
  }
})
body {
  background-color: grey;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.container button {
  width: 100px;
  height: 100px;  
}

@keyframes btn {
  0% {
    margin-top: 50px;
  }
  50% {
    margin-top: 60px;
  }
  100% {
    margin-top: 0;
  }
}

button.on {
  animation: btn 900ms linear ;
}
<div class="container">
    <button>Stick</button>
  </div>

  1. Решение: придётся делать анимацию через js

UPD:

  1. Нашел, что можно всё же отследить анимацию https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/animationend_event

let btn = document.querySelector("button")

btn.addEventListener("click", function () {
  if (!btn.classList.contains("on")) {
    btn.classList.add("on");
    
    let animatedButton = document.querySelector('button.on');
    animatedButton.onanimationend = () => {
      btn.classList.remove("on");
    };
  }
})
body {
  background-color: grey;
}

.container {
  height: 100vh;
  display: flex;
  flex-direction: row;
  justify-content: center;
  align-items: center;
}

.container button {
  width: 100px;
  height: 100px;  
}

@keyframes btn {
  0% {
    margin-top: 50px;
  }
  50% {
    margin-top: 60px;
  }
  100% {
    margin-top: 0;
  }
}

button.on {
  animation: btn 900ms linear ;
}
<div class="container">
    <button>Stick</button>
  </div>

2
  • Спасибо огромное
    – Epic Game
    5 авг 2021 в 14:36
  • @EpicGame добавил третий ответ в конец. Там именно отслеживание окончание анимации есть 5 авг 2021 в 14:37

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.