首页 > 解决方案 > 悬停效果的图像不会保持可见

问题描述

您好,提前感谢您阅读我的问题。

目标:设置图像,以便一旦它滚动到视图中,它就会平滑地过渡到设置的位置 - 但仍然会对:hover. 使用@keyframes一点 JavaScript,我将图像设置为opacity: 0最终不透明度为opacity: .85. 然后我在 CSS 中添加了悬停效果以使其成为opacity: 1

问题是一旦它完成了它的过渡 - 它就会消失 - 恢复到它的原始不透明度为零。我设法让它冻结在.85animation-fill-mode: forwards而不是animation-fill-mode: none,但它不会响应:hover

这是实际问题的测试片段:

let observer_img = new IntersectionObserver(updates => {
    updates.forEach(update => {
        if (update.isIntersecting) {
            update.target.classList.add('shift_frame_center_img');
        } else {
            update.target.classList.remove('shift_frame_center_img');
        }
    });
}, { threshold: 0 });

[...document.querySelectorAll('.features-img-wrapper img')].forEach(element => observer_img.observe(element));
body {
  width: 100%;
  height: 100vh;
  background-color: lightgrey;
}

/* CHILD */
.features-img-wrapper img {
  width: 10rem;
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-top: 8rem;
  opacity: 0;
  transition: all .5s;
}

/* APPEND-CHILD */
.shift_frame_center_img {
  animation: center_img 1s 0.5s none;
}

/* CHILD ON HOVER */
.features-img-wrapper img:hover {
  opacity: 1;
  transform: scale(1.035);
}

/* KEYFRAMES */
@keyframes center_img {
  0% {
    transform: translateY(20rem);
  }
  100% {
    transform: translateY(0);
    opacity: .85;
  }
}
<body>
  <div class="features-img-wrapper">
      <img src="https://synapse.it/wp-content/uploads/2020/12/test.png">
  </div>
</body>

如果我能帮上忙,那就太好了,我有点初学者,已经花了几个小时,欢迎所有反馈。非常感谢。

标签: javascripthtmlcssuser-interfaceanimation

解决方案


解决方案 1

要了解为什么悬停效果不适用于animation-fill-mode: forwards,请阅读此答案

您可以通过向!important悬停样式添加属性来解决此问题:

.features-img-wrapper img:hover {
  opacity: 1 !important;
  transform: scale(1.035) !important;
}

在这种情况下,问题是过渡不适用于悬停。

解决方案 2

您可以完全删除动画并将最终状态样式添加到shift_frame_center_img类中。

!important但是由于CSS Specificity,您仍然需要使用该属性。

let observer_img = new IntersectionObserver(updates => {
    updates.forEach(update => {
        if (update.isIntersecting) {
            update.target.classList.add('shift_frame_center_img');
        } else {
            update.target.classList.remove('shift_frame_center_img');
        }
    });
}, { threshold: 0 });

[...document.querySelectorAll('.features-img-wrapper img')].forEach(element => observer_img.observe(element));
body {
  width: 100%;
  height: 100vh;
  background-color: lightgrey;
}

/* CHILD */
.features-img-wrapper img {
  width: 10rem;
  transform: translateY(20rem);
  display: block;
  margin-left: auto;
  margin-right: auto;
  margin-top: 8rem;
  opacity: 0;
  transition: all .5s;
}

/* APPEND-CHILD */
.shift_frame_center_img {
  transform: none !important;
  opacity: .85 !important;
}

/* CHILD ON HOVER */
.features-img-wrapper img:hover {
  opacity: 1 !important;
  transform: scale(1.035) !important;
}
<body>
  <div class="features-img-wrapper">
    <img src="https://synapse.it/wp-content/uploads/2020/12/test.png">
  </div>
</body>


推荐阅读