微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

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

如果您想使用 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>

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。