Переход не работает, если существует свойство анимации - PullRequest
2 голосов
/ 07 мая 2020

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

@keyframes hours {
  to {
    transform: rotate(360deg);
  }
}
#watch .hours-hand {
  width: 0.8em;
  height: 7em;
  background: #232425;
  position: absolute;
  bottom: 50%;
  left: 50%;
  margin: 0 0 -0.8em -0.4em;
  box-shadow: #232425 0 0 2px;
  transform-origin: 0.4em 6.2em;
  transform: rotate(0deg);
  transition: all 1s;
}
var changeTime = (date) => {
  const hoursHand = document.querySelector(".hours-hand");
  const minutesHand = document.querySelector(".minutes-hand");

  const minutes = date.getMinutes();
  const hours = date.getHours();

  const newMinutes = (360 / 60) * minutes;
  const newHours = (360 / 12) * hours;

  hoursHand.style.transform = `rotate(${newHours}deg)`;
  minutesHand.style.transform = `rotate(${newMinutes}deg)`;
};

1 Ответ

1 голос
/ 07 мая 2020

Вы можете просто добавить оболочку вокруг элементов, у которых уже есть свойство animation, и вместо этого повернуть эту оболочку:

const watch = document.getElementById('watch');
const changeTimeButton = document.getElementById('changeTimeButton');

let shift = 0;

changeTimeButton.onclick = (date) => {
  shift = (shift + 360 / 12) % 360;
  
  watch.style.transform = `rotate(${ shift }deg)`;
};
@keyframes hours {
  to {
    transform: rotate(360deg);
  }
}

body {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
  margin: 0;
}

#changeTimeButton {
  margin-top: 16px;
}

#watch {  
  position: relative;
  box-shadow: 0 0 32px 0 rgba(0, 0, 0, .125);
  border-radius: 100%;
  width: 50vh;
  height: 50vh;
}

.hours-hand {
  position: absolute;
  top: 8px;
  bottom: 50%;
  left: calc(50% - 2px);
  width: 4px;
  background: #232425;
  transform-origin: 50% 100%;
  animation-name: hours;
  animation-duration: 5s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}
<div id="watch">
  <div class="hours-hand"></div>
</div>

<button id="changeTimeButton">Change Time</button>
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...