请求实现鼠标悬停切换并垂直滚动的图片链接交互效果
实现悬停切换图片并垂直滚动长图的交互效果
需求说明
需要创建带鼠标悬停交互的图片链接,实现以下效果:
- 常态下显示顶部缩略图
- 鼠标悬停时,隐藏顶部缩略图,显示底部长图
- 长图在固定的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`); }
关键改动说明
- 结构调整:容器内新增顶部缩略图元素,与长图分层级放置,通过
z-index控制显示优先级 - 切换逻辑:用CSS的
opacity过渡实现悬停时的图片切换,替代原有单一图片的动画逻辑,精准匹配需求 - 滚动优化:使用
transform: translateY实现长图滚动,性能优于修改top属性;动画终点动态计算,确保长图底部刚好显示在容器内 - 动态适配:JS根据长图实际高度计算动画时长,不同长度的长图能保持一致的滚动速度
内容的提问来源于stack exchange,提问作者JStormThaKid
相关产品推荐
相关产品推荐

