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

Swiper横向滑块菜单点击后无法保留active类的问题求助

Swiper横向滑块菜单点击后无法保留active类的问题求助

嘿,我看你遇到的问题是点击滑块菜单后,active类能立刻生效,但页面刷新就没了对吧?这问题出在你用localStorage存储的内容不对——你现在存的只是个布尔值,根本没法定位到具体是哪个滑块被选中了,咱们调整下逻辑就能搞定。

先说说你当前代码的问题:
你用localStorage.setItem('toggleState', $(this).hasClass('active'));存了个true,之后读取的时候还试图通过#加这个布尔值找元素,这完全不匹配,自然恢复不了状态。咱们得存能唯一标识被点击滑块的信息,比如滑块里链接的href,或者滑块的索引。

给你改好的代码,直接替换原来的script部分就行:

$(document).ready(function() {
  // 页面加载时先恢复之前的选中状态
  const savedActiveHref = localStorage.getItem('activeSwiperSlide');
  if (savedActiveHref) {
    // 找到对应href的链接所在的滑块,添加active类
    $('.swiper-slide .sof-swiper-link[href="' + savedActiveHref + '"]').closest('.swiper-slide').addClass('active');
  } else {
    // 如果没有存储的状态,默认给第一个滑块加active(和你初始设置一致)
    $('.swiper-slide').first().addClass('active');
  }

  // 绑定滑块点击事件
  $(".swiper-slide").click(function() {
    // 切换active类
    $(this).addClass("active").siblings().removeClass("active");
    // 存储当前选中滑块的链接href作为标识
    const activeHref = $(this).find(".sof-swiper-link").attr("href");
    localStorage.setItem('activeSwiperSlide', activeHref);
  });   
});

如果你的菜单里有可能出现重复的href(虽然理论上不会),那可以改用滑块的索引来存储,代码改成这样:

$(document).ready(function() {
  // 页面加载恢复状态
  const savedIndex = localStorage.getItem('activeSwiperSlideIndex');
  if (savedIndex !== null) {
    $('.swiper-slide').eq(savedIndex).addClass('active').siblings().removeClass('active');
  } else {
    $('.swiper-slide').first().addClass('active');
  }

  // 点击事件
  $(".swiper-slide").click(function() {
    $(this).addClass("active").siblings().removeClass("active");
    // 存储当前滑块的索引
    const activeIndex = $(this).index();
    localStorage.setItem('activeSwiperSlideIndex', activeIndex);
  });   
});

这样修改后,不管页面怎么刷新,之前选中的滑块都会保留active类啦。原理就是把选中元素的唯一标识存在localStorage里,页面加载时再根据这个标识找到对应元素添加样式。

备注:内容来源于stack exchange,提问作者user28928120

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.14 13:12:59