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

如何让Owl Carousel切换item的函数在首尾项时停止执行?

解决方法

核心逻辑是切换前先判断当前激活项所在的.owl-item是否为列表首尾,如果是直接终止函数执行,不做移除类的操作。
修改后的上一页切换代码:

// Go to the previous item
$(".owl-prev-custom").click(function () {
  const $activeItem = $(".owl-carousel-timeline .item.item-year-active");
  const $currentOwlItem = $activeItem.parent();

  // 到达首项直接停止执行
  if ($currentOwlItem.is(":first-child")) return;

  $activeItem.removeClass("item-year-active");
  $currentOwlItem.prev().children(".item").addClass("item-year-active");

  const theHash = $(".owl-carousel-timeline .item.item-year-active").attr("data-hash");
  // 此处保留你原本对theHash的后续处理逻辑
});

如果需要同步修复下一页切换的边界问题,可直接使用如下代码:

// Go to the next item
$(".owl-next-custom").click(function () {
  const $activeItem = $(".owl-carousel-timeline .item.item-year-active");
  const $currentOwlItem = $activeItem.parent();

  // 到达末项直接停止执行
  if ($currentOwlItem.is(":last-child")) return;

  $activeItem.removeClass("item-year-active");
  $currentOwlItem.next().children(".item").addClass("item-year-active");

  const theHash = $(".owl-carousel-timeline .item.item-year-active").attr("data-hash");
  // 此处保留你原本对theHash的后续处理逻辑
});

原理解释

你之前的代码会先移除激活类,再尝试查找相邻节点,当已经处于首尾位置时,相邻节点不存在,就没有元素可以添加激活类,最终导致类丢失。现在把边界判断放在最前面,命中边界条件时直接中断函数,不会执行后续的类修改操作,自然就不会出现类丢失的问题。

内容的提问来源于stack exchange,提问作者z-1881

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 07:36:04