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

如何实现marquee中悬停图片固定、其余图片继续滚动的效果?

嘿,这个需求挺有意思的!不过得先提一句,<marquee>标签其实已经被HTML标准废弃啦,它的可控性和兼容性都不太好,咱们用CSS动画+JavaScript来实现会更靠谱,也更灵活。

实现核心思路

核心逻辑是让所有图片在一个滚动容器里持续横向滚动,当鼠标悬停某张图片时,把这张图片从滚动流中“抽离”出来——用绝对定位固定在当前位置,同时提高层级让它显示在其他图片上方;鼠标离开时,再把它放回滚动流,跟着大部队继续动。

具体实现代码

HTML结构

咱们不用<marquee>,改用一个容器包裹每个图片的独立容器,还重复了一组图片来让滚动更连贯(避免滚动到末尾出现空白):

<div class="scroll-container">
  <div class="scroll-item">
    <img src="img1.jpg" alt="图片1">
  </div>
  <div class="scroll-item">
    <img src="img2.jpg" alt="图片2">
  </div>
  <div class="scroll-item">
    <img src="img3.jpg" alt="图片3">
  </div>
  <!-- 重复图片组,让滚动无间断 -->
  <div class="scroll-item">
    <img src="img1.jpg" alt="图片1">
  </div>
  <div class="scroll-item">
    <img src="img2.jpg" alt="图片2">
  </div>
  <div class="scroll-item">
    <img src="img3.jpg" alt="图片3">
  </div>
</div>

CSS样式

实现滚动动画,同时给悬停固定的图片准备专属样式:

.scroll-container {
  display: flex;
  overflow: hidden;
  width: 100%;
  gap: 15px; /* 图片之间的间距,可自定义 */
  position: relative;
}

.scroll-item {
  flex-shrink: 0; /* 防止图片被压缩 */
  animation: scroll-left 12s linear infinite; /* 12s是滚动时长,数值越小速度越快 */
  position: relative;
}

.scroll-item img {
  width: 220px; /* 自定义图片宽度 */
  height: auto;
  cursor: pointer;
}

/* 悬停时的固定样式 */
.scroll-item.fixed {
  position: absolute;
  z-index: 10; /* 让固定的图片显示在其他图片上方 */
  animation-play-state: paused; /* 暂停自身滚动动画 */
}

/* 向左滚动的动画关键帧 */
@keyframes scroll-left {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-100%);
  }
}

JavaScript交互逻辑

处理每个图片的悬停/离开事件,实现固定和恢复滚动的效果:

const scrollItems = document.querySelectorAll('.scroll-item');
const scrollContainer = document.querySelector('.scroll-container');

scrollItems.forEach(item => {
  // 鼠标悬停时固定当前图片
  item.addEventListener('mouseover', function() {
    // 计算当前图片相对于容器的位置
    const itemRect = this.getBoundingClientRect();
    const containerRect = scrollContainer.getBoundingClientRect();
    const leftOffset = itemRect.left - containerRect.left;
    // 设置固定位置并添加样式类
    this.style.left = `${leftOffset}px`;
    this.classList.add('fixed');
  });

  // 鼠标离开时恢复滚动
  item.addEventListener('mouseout', function() {
    this.classList.remove('fixed');
    this.style.left = ''; // 清除自定义位置
  });
});
小技巧调整
  • 如果需要从右往左滚动,只需要把CSS动画里的scroll-left关键帧修改:
    @keyframes scroll-right {
      0% {
        transform: translateX(-100%);
      }
      100% {
        transform: translateX(0);
      }
    }
    
    然后把.scroll-item的animation改成scroll-right 12s linear infinite就行。
  • 要是图片数量很多,可以用JS动态克隆初始的图片组,不用手动重复写HTML。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.14 08:39:22