You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

请求实现鼠标悬停切换并垂直滚动的图片链接交互效果

实现悬停切换图片并垂直滚动长图的交互效果

需求说明

需要创建带鼠标悬停交互的图片链接,实现以下效果:

  • 常态下显示顶部缩略图
  • 鼠标悬停时,隐藏顶部缩略图,显示底部长图
  • 长图在固定的400x328px区域内垂直平滑滚动,适配任意长度的长图(如400x755px等)

修改后的实现代码

HTML

<div class="container">
  <div class="row">
    <div class="col mt-3">
      <div class="scrolling-window">
        <!-- 顶部缩略图 -->
        <img src="https://place-hold.it/400x328" alt="缩略图" class="top-image" />
        <!-- 底部长图 -->
        <img onload="initProps(this)" class="scrolling-image" src="https://place-hold.it/400x755" />
      </div>
    </div>
    <div class="col mt-3">
      <div class="scrolling-window">
        <img src="https://place-hold.it/400x328" alt="缩略图" class="top-image" />
        <img onload="initProps(this)" class="scrolling-image" src="https://place-hold.it/400x1132" />
      </div>
    </div>
  </div>
</div>

CSS

.container {
  padding: 10px 0;
}

.scrolling-window {
  border-radius: 10px;
  display: block;
  width: 400px;
  height: 328px;
  overflow: hidden;
  position: relative;
  border: 2px solid #b3b3b3;
  margin: 0 auto;
  cursor: pointer;
}

/* 顶部缩略图样式 */
.top-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 1;
  transition: opacity 0.3s ease;
}

/* 长图默认隐藏 */
.scrolling-image {
  width: 100%;
  height: auto;
  position: absolute;
  top: 0;
  left: 0;
  z-index: 0;
  opacity: 0;
  transition: opacity 0.3s ease;
}

/* 悬停时切换图片并触发滚动 */
.scrolling-window:hover .top-image {
  opacity: 0;
}

.scrolling-window:hover .scrolling-image {
  opacity: 1;
  animation: scroll var(--animation-duration) cubic-bezier(0.4, 0, 0.6, 1) infinite alternate;
}

/* 长图垂直滚动动画 */
@keyframes scroll {
  from {
    transform: translateY(0);
  }
  to {
    transform: translateY(calc(-100% + 328px));
  }
}

JavaScript

function initProps(el) {
  const scrollSpeed = 0.006; // 滚动速度系数,数值越小滚动越慢
  const imageHeight = el.naturalHeight;
  // 根据长图超出容器的高度计算动画时长,保证不同长度长图滚动速度一致
  const animationDuration = Math.round((imageHeight - 328) * scrollSpeed * 1000);
  el.style.setProperty("--animation-duration", `${animationDuration}ms`);
}

关键改动说明

  1. 结构调整:容器内新增顶部缩略图元素,与长图分层级放置,通过z-index控制显示优先级
  2. 切换逻辑:用CSS的opacity过渡实现悬停时的图片切换,替代原有单一图片的动画逻辑,精准匹配需求
  3. 滚动优化:使用transform: translateY实现长图滚动,性能优于修改top属性;动画终点动态计算,确保长图底部刚好显示在容器内
  4. 动态适配:JS根据长图实际高度计算动画时长,不同长度的长图能保持一致的滚动速度

内容的提问来源于stack exchange,提问作者JStormThaKid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.22 22:10:00