如何实现Prev/Next按钮同步切换map-inr与global_map_location的类
问题解决:点击Prev/Next按钮同步更新地图导航的类状态
你遇到的核心问题是只给目标元素添加类,但未先清除所有同类元素的对应类,导致旧元素的样式无法被覆盖。以下是修正后的实现方案:
核心思路
- 每次切换前,先统一移除所有
.map-inr的active类和.global_map_location的scale_text类 - 通过当前显示的
.map-item的索引,匹配对应位置的.global-map容器,为其内部元素添加类 - 保留原有
.map-item的切换逻辑,确保导航与内容区域的状态完全同步
修正后的完整JS代码
// Open Popup(保留原有逻辑,修正索引偏移问题) $(".map-inr").on("click", function () { let myIndex = $(this).closest(".global-map").index(); $('.map-inr').removeClass('active'); $(this).addClass('active'); $('.global_map_location').removeClass('scale_text'); $(this).closest(".global-map").find('.global_map_location').addClass('scale_text'); if ($(".map-item.is--show").length) { $(".map-item").removeClass("is--show"); setTimeout(function () { $(".map-item").eq(myIndex).addClass("is--show"); }, 600); } else { $(".map-item").eq(myIndex).addClass("is--show"); } }); // Next function(修正版本) $('.next').click(function(){ const currentIndex = $(".map-item.is--show").index(); const nextIndex = currentIndex + 1; // 先清除所有元素的状态类 $('.map-inr').removeClass('active'); $('.global_map_location').removeClass('scale_text'); // 判断下一个元素是否存在 if ($(".map-item").eq(nextIndex).length) { // 为对应位置的地图导航添加状态类 $(".global-map").eq(nextIndex).find('.map-inr').addClass("active"); $(".global-map").eq(nextIndex).find('.global_map_location').addClass("scale_text"); // 切换内容区域的显示状态 $('.is--show').removeClass('is--show') .next('.map-item') .addClass('is--show'); } }); // Prev function(修正版本) $('.prev').click(function(){ const currentIndex = $(".map-item.is--show").index(); const prevIndex = currentIndex - 1; // 先清除所有元素的状态类 $('.map-inr').removeClass('active'); $('.global_map_location').removeClass('scale_text'); // 判断上一个元素是否存在 if ($(".map-item").eq(prevIndex).length) { // 为对应位置的地图导航添加状态类 $(".global-map").eq(prevIndex).find('.map-inr').addClass("active"); $(".global-map").eq(prevIndex).find('.global_map_location').addClass("scale_text"); // 切换内容区域的显示状态 $('.is--show').removeClass('is--show') .prev('.map-item') .addClass('is--show'); } });
关键修改点说明
- 移除了原代码中
myIndex = $(this).closest(".global-map").index() - 1的减1操作:.global-map和.map-item的索引是一一对应的(第一个地图导航对应第一个内容块),无需偏移 - 每次切换前全局清除状态类:避免旧元素的样式残留,确保只有目标元素保留高亮状态
- 通过当前显示的
.map-item索引定位导航元素:保证导航与内容区域的状态完全同步
额外优化建议
可将重复的状态清除逻辑封装为函数,减少代码冗余:
function resetMapStates() { $('.map-inr').removeClass('active'); $('.global_map_location').removeClass('scale_text'); } // 在Next/Prev函数中调用即可 resetMapStates();
内容的提问来源于stack exchange,提问作者laurence keith albano
相关产品推荐
相关产品推荐

