悬停和反向悬停时的 CSS 背景图像位置动画

时间:2021-02-01 19:25:46

标签: css animation reverse pause

如果您想使用 Css 动画制作图像背景位置从右到左和/或从右到左悬停相关按钮的动画,似乎不可能获得正确的视觉效果。

问题在于,如果 1) 将鼠标悬停在左按钮上 2) 将鼠标悬停在外以暂停 3) 再次将鼠标悬停在左按钮上,动画会顺利重新开始,但是如果您使用右键尝试相同的操作,则第一个您看到的帧不是暂停的帧,而是动画中的第一帧。

.btn {
  position: absolute;
  z-index: 1;
  top: 50%;
  transform: translateY(-50%);
}
.btn.left {
  left: 0;
}
.btn.right {
  right: 0;
}

.masked-background {
  height: 400px;
  position: relative;
  width: 500px;
}
.masked-background-image {
  position: absolute;
  width: 100%;
  height: 100%;
  top: 0;
  right: 0;
  bottom: 0;
  left: 0;
  background-repeat: no-repeat;
  background-size: auto 400px;
  background-position: 0;
}
.masked-background .animated-on-hover {
  animation-name: backgroundMove;
  animation-duration: 7s;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
  animation-fill-mode: both;
  animation-direction: alternate-reverse;
  animation-play-state: paused;
}
.masked-background .animation-trigger {
  z-index: 1;
}
.masked-background .animation-trigger:hover ~ .animated-on-hover {
  animation-play-state: running;
}
.masked-background .animation-trigger.animation-reverse:hover ~ .animated-on-hover {
  animation-direction: reverse;
}
.masked-background .animation-trigger.animation-normal:hover ~ .animated-on-hover {
  animation-direction: normal;
}

@keyframes backgroundMove {
  0% {
    background-position: 0;
  }
  100% {
    background-position: 100%;
  }
}
<div class="masked-background">
    <button type="button"
        class="btn left animation-trigger animation-reverse">Left
    </button>
    <button type="button"
            class="btn right animation-trigger animation-normal">Right</button>
   
    <div class="masked-background-image animated-on-hover" style="background-image: url('https://www.terredainventare.it/images/test.jpg');">
    </div>
</div>

0 个答案:

没有答案