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

如何实现带固定自定义滚动按钮的可滚动缩略图托盘?

解决方案

核心思路

  • 父容器设为position: relative,作为滚动按钮的定位基准
  • 滚动按钮用position: absolute固定在父容器两侧,脱离文档流,不会随托盘滚动
  • 内部托盘容器开启水平滚动并隐藏原生滚动条
  • 通过JavaScript绑定按钮事件,控制托盘滚动距离

完整代码实现

HTML

<div class="thumbnail-container">
  <button class="scroll-btn scroll-left">&lt;</button>
  <div class="scroll-tray">
    <div class="tray-content">
      <a href="#" class="thumbnail">图1</a>
      <a href="#" class="thumbnail">图2</a>
      <a href="#" class="thumbnail">图3</a>
      <a href="#" class="thumbnail">图4</a>
      <a href="#" class="thumbnail">图5</a>
      <a href="#" class="thumbnail">图6</a>
      <a href="#" class="thumbnail">图7</a>
      <a href="#" class="thumbnail">图8</a>
      <a href="#" class="thumbnail">图9</a>
      <a href="#" class="thumbnail">图10</a>
    </div>
  </div>
  <button class="scroll-btn scroll-right">&gt;</button>
</div>

CSS

.thumbnail-container {
  position: relative;
  width: 400px;
  margin: 20px auto;
}

.scroll-tray {
  width: 100%;
  overflow-x: auto;
  /* 隐藏原生滚动条 */
  scrollbar-width: none; /* Firefox */
  -ms-overflow-style: none; /* IE/Edge */
}

/* Chrome/Safari/Opera 隐藏滚动条 */
.scroll-tray::-webkit-scrollbar {
  display: none;
}

.tray-content {
  display: flex;
  gap: 10px;
  padding: 10px 0;
  width: max-content; /* 内容宽度自适应,超出父容器触发滚动 */
}

.thumbnail {
  display: block;
  width: 80px;
  height: 80px;
  background-color: #ddd;
  text-align: center;
  line-height: 80px;
  text-decoration: none;
  color: #333;
}

.scroll-btn {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 30px;
  height: 30px;
  border: none;
  background-color: rgba(0,0,0,0.5);
  color: white;
  cursor: pointer;
  z-index: 10; /* 保证按钮在托盘上方,不被遮挡 */
}

.scroll-left {
  left: 10px;
}

.scroll-right {
  right: 10px;
}

JavaScript

const scrollTray = document.querySelector('.scroll-tray');
const scrollLeftBtn = document.querySelector('.scroll-left');
const scrollRightBtn = document.querySelector('.scroll-right');

// 单次滚动距离
const scrollStep = 150;

scrollLeftBtn.addEventListener('click', () => {
  scrollTray.scrollBy({
    left: -scrollStep,
    behavior: 'smooth' // 平滑滚动,可移除改为瞬间滚动
  });
});

scrollRightBtn.addEventListener('click', () => {
  scrollTray.scrollBy({
    left: scrollStep,
    behavior: 'smooth'
  });
});

关键说明

  1. 按钮固定:父容器的position: relative让按钮的绝对定位基于父容器,不会随内部托盘滚动偏移
  2. 滚动条隐藏:通过浏览器私有属性隐藏原生滚动条,同时保留滚动功能
  3. 交互保障:按钮设置z-index:10确保在托盘内容上方,不会被<a>元素遮挡,<a>的点击功能完全正常
  4. 滚动控制:scrollBy方法支持平滑滚动,可根据需求调整滚动距离或移除平滑效果

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.02 01:42:28