点击菜单元素时为另一容器同位置元素添加disabled类的需求
解决方案
我来帮你搞定这个菜单交互需求!目前你的代码已经实现了点击元素切换active类并移除同级元素的active,但还缺了跨菜单添加disabled类的逻辑,咱们一步步完善:
核心思路
- 点击某个菜单元素时,先获取它在父容器里的索引位置(两个菜单的子元素位置一一对应)
- 找到另一个菜单容器,定位到相同索引的元素,根据当前元素的
active状态来切换它的disabled类 - 同时要清理另一个菜单里其他元素的
disabled类,避免残留状态
修改后的完整代码
HTML
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.2.3/jquery.min.js"></script> <div class="container"> <div class="selection left"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> <div class="selection right"> <div>1</div> <div>2</div> <div>3</div> <div>4</div> <div>5</div> </div> </div>
CSS
.selection{ display: inline-block; margin: 0 20px; } .selection div{ background-color: #DDD; width: 40px; height: 40px; text-align: center; line-height: 40px; border-radius: 100px; cursor: pointer; margin: 5px 0; } .selection div.active{ background-color: green; color: #FFF; } .selection div.disabled{ background-color: red; color: #FFF; cursor: not-allowed; }
JavaScript
$(document).ready(function(){ $('.selection div').click(function(){ // 切换当前元素的active类,移除同级的active $(this).toggleClass('active').siblings().removeClass('active'); // 获取当前元素在父容器中的索引 const currentIndex = $(this).index(); // 找到另一个菜单容器 const otherSelection = $(this).parents('.selection').siblings('.selection'); // 如果当前元素是active状态,给对应位置加disabled,否则移除 if($(this).hasClass('active')){ otherSelection.find('div').removeClass('disabled').eq(currentIndex).addClass('disabled'); } else { otherSelection.find('div').eq(currentIndex).removeClass('disabled'); } }); });
关键代码解释
$(this).index():获取点击元素在父容器子元素中的位置(从0开始计数)$(this).parents('.selection').siblings('.selection'):定位到另一个同级的菜单容器,不管是左还是右菜单都能适配otherSelection.find('div').removeClass('disabled').eq(currentIndex).addClass('disabled'):先清除另一个菜单所有元素的disabled状态,再给对应位置的元素加上disabled- 最后通过判断当前元素的active状态,决定是添加还是移除对应元素的disabled类,实现点击取消active时,另一边的disabled也同步取消
内容的提问来源于stack exchange,提问作者user6689442
相关产品推荐
相关产品推荐

