如何用jQuery实现动态.tmb元素批量hover交互与分组背景变色?
解决方案:动态元素悬停过滤+循环背景色切换
问题回顾
现有代码仅支持前两个.tmb元素互斥悬停过滤,现在需要升级为:
- 悬停任意
.tmb时,其余所有(含动态增减的).tmb都加上.filtered类 .style-light-bg的背景色按.tmb位置每5个一组循环5种颜色
第一步:CSS 准备
先定义好5种循环颜色和过滤样式:
/* 5种循环背景色,对应每5个元素一轮 */ .color-group-0 { background-color: #ff4444; } /* 第1、6、11...个元素 */ .color-group-1 { background-color: #33b5e5; } /* 第2、7、12...个元素 */ .color-group-2 { background-color: #99cc00; } /* 第3、8、13...个元素 */ .color-group-3 { background-color: #ffbb33; } /* 第4、9、14...个元素 */ .color-group-4 { background-color: #aa66cc; } /* 第5、10、15...个元素 */ /* 过滤状态样式,按需调整 */ .tmb.filtered { opacity: 0.5; pointer-events: none; /* 可选:避免过滤元素触发悬停 */ } .style-light-bg { transition: background-color 0.3s ease; background-color: #ffffff; /* 默认背景色 */ }
第二步:JS 逻辑实现
用事件委托处理动态元素,同时计算位置索引切换颜色:
// 核心容器(如果.tmb都在某个父容器里,替换成你的容器选择器,否则用document) const tmbContainer = document.querySelector('.tmb-container') || document; const lightBgElement = document.querySelector('.style-light-bg'); // 颜色类数组,和CSS对应 const colorGroups = ['color-group-0', 'color-group-1', 'color-group-2', 'color-group-3', 'color-group-4']; // 悬停事件处理 tmbContainer.addEventListener('mouseover', (e) => { const hoveredTmb = e.target.closest('.tmb'); if (!hoveredTmb) return; // 给所有.tmb加过滤类,再移除当前悬停元素的过滤类 document.querySelectorAll('.tmb').forEach(tmb => tmb.classList.add('filtered')); hoveredTmb.classList.remove('filtered'); // 计算当前元素的位置(从0开始计数) const allTmbs = Array.from(document.querySelectorAll('.tmb')); const tmbIndex = allTmbs.indexOf(hoveredTmb); // 取模5得到颜色组索引 const colorIndex = tmbIndex % 5; // 切换背景色类 lightBgElement.classList.remove(...colorGroups); lightBgElement.classList.add(colorGroups[colorIndex]); }); // 离开事件处理 tmbContainer.addEventListener('mouseout', (e) => { const hoveredTmb = e.target.closest('.tmb'); if (!hoveredTmb) return; // 移除所有过滤类和背景色类 document.querySelectorAll('.tmb').forEach(tmb => tmb.classList.remove('filtered')); lightBgElement.classList.remove(...colorGroups); // 可选:恢复默认背景色 // lightBgElement.style.backgroundColor = '#ffffff'; });
关键细节说明
- 动态元素兼容:事件绑定在父容器(或全局)上,不管后续新增还是删除
.tmb,都能正常触发悬停逻辑; - 颜色循环逻辑:通过
元素索引 % 5实现每5个元素一轮的颜色循环,索引从0开始,对应第1个元素索引为0,正好匹配color-group-0; - 过滤逻辑:先给所有元素加过滤类,再移除当前元素的类,确保只有悬停的元素保持正常状态。
内容的提问来源于stack exchange,提问作者CliffVandyck
相关产品推荐
相关产品推荐

