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

基于Slick Carousel实现时间线交互效果:为所有前置幻灯片添加持久着色样式

解决Slick Carousel时间线前置幻灯片着色问题

我来帮你搞定这个时间线的交互需求!你现在遇到的问题是只能处理紧邻的上一个幻灯片,没法批量选中所有前置项,咱们可以通过新增状态类+切换时批量更新的方式解决。

步骤1:新增CSS状态类

首先咱们给已浏览过的前置幻灯片加一个专属的.completed类,让它和当前选中项保持一致的着色风格:

.wrapper {
  max-width: 800px;
}
.slick-list {
  width: 100%;
}
.carrousel__candidature__timeline {
  .timeline-item {
    width: auto;
    height: auto;
    background: transparent;
    margin-bottom: 20px !important;
    position: relative;
    font-size: 14px;
    line-height: 28px;
    font-weight: 400;
    outline: none;
    cursor: pointer;
    color: grey;
    &::before {
      content: "";
      position: absolute;
      top: 36px;
      left: -100%;
      width: 100%;
      height: 2px;
      background-color: grey;
      transition: 0.2s;
    }
    &::after {
      content: "";
      position: absolute;
      top: 30px;
      left: 0;
      width: 15px;
      height: 15px;
      border-radius: 100%;
      background-color: grey;
      transition: 0.2s;
      z-index: 1000;
    }
    &.slick-current {
      color: red;
    }
    &.slick-current::before {
      background-color: red;
    }
    &.slick-current::after {
      background-color: red;
    }
    /* 新增已完成项样式 */
    &.completed {
      color: red;
    }
    &.completed::before {
      background-color: red;
    }
    &.completed::after {
      background-color: red;
    }
  }
}

步骤2:修改JS逻辑,批量更新前置项状态

接下来咱们在Slick的onAfterChange事件里,根据当前幻灯片的索引,批量给所有前置项添加/移除.completed类。另外注意你之前的代码里有个拼写错误:SlideToScroll应该是小写开头的slidesToScroll,这个要修正:

$('.carrousel__candidature__timeline').slick({
  slidesToShow: 4,
  slidesToScroll: 1, // 修正拼写错误
  asNavFor: '.carrousel__candidature__content',
  centerMode: false,
  focusOnSelect: true,
  mobileFirst: true,
  arrows: false,
  dots: false,
  infinite: false,
  variableWidth: false,
  onAfterChange: function(slick, currentSlide) {
    // 先清空所有已完成状态
    $('.timeline-item').removeClass('completed');
    // 获取当前幻灯片的索引
    const currentIndex = currentSlide.currentSlide;
    // 遍历所有时间线项,给索引小于当前的项添加已完成类
    $('.timeline-item').each(function(index) {
      if (index < currentIndex) {
        $(this).addClass('completed');
      }
    });
  }
});

效果说明

这样修改后:

  • 向前切换到某张幻灯片时,所有在它之前的幻灯片都会自动变成红色(已浏览状态)
  • 向后切换时,超出当前索引的幻灯片会自动恢复灰色,而当前索引之前的仍然保持红色
  • 点击任意幻灯片时,同样会自动把它之前的所有项标记为已浏览状态

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.29 19:07:45