如何用JavaScript实现Twig循环中点击div仅修改当前选中项背景色
解决方案
问题原因
现有代码仅对当前点击的div做背景色切换,没有重置之前选中的div的背景色,因此每次点击都会新增一个蓝色背景的div,出现同时选中多个的现象。
方案1:变量记录上一次选中元素(最小改动适配原有逻辑)
不需要调整Twig代码,直接修改JavaScript即可:
<script> // 存储上一次选中的元素id let lastSelectedId = null; function viewMessage(elementId) { // 先重置上一个选中元素的背景色 if (lastSelectedId && lastSelectedId !== elementId) { document.getElementById(lastSelectedId).style.backgroundColor = "rgb(235, 235, 235)"; } const currentEl = document.getElementById(elementId); const currentBg = window.getComputedStyle(currentEl).backgroundColor; if (currentBg === "rgb(235, 235, 235)") { currentEl.style.backgroundColor = "blue"; lastSelectedId = elementId; } else { currentEl.style.backgroundColor = "rgb(235, 235, 235)"; // 取消选中当前元素时清空记录 lastSelectedId = null; } } </script>
方案2:用CSS类控制(更易维护的推荐方案)
不需要硬编码颜色值,后续调整样式只需要修改CSS即可:
- 新增CSS样式
/* 聊天项选中态样式 */ .chat_list.active { background-color: blue; }
- 修改JavaScript代码
<script> function viewMessage(elementId) { const currentEl = document.getElementById(elementId); // 先移除所有聊天项的选中态 document.querySelectorAll('.chat_list').forEach(el => { if (el.id !== elementId) el.classList.remove('active'); }); // 切换当前元素选中态,点击已选中的元素可取消选中 currentEl.classList.toggle('active'); } </script>
可选优化:事件委托减少绑定
如果聊天列表元素数量较多,可以去掉Twig中每个div绑定的onclick属性,改用事件委托提升性能:
<script> document.querySelector('.inbox_chat').addEventListener('click', (e) => { // 匹配点击的聊天项元素 const chatItem = e.target.closest('.chat_list'); if (!chatItem) return; // 重置所有元素选中态 document.querySelectorAll('.chat_list').forEach(el => { if (el !== chatItem) el.classList.remove('active'); }); // 切换当前元素选中态 chatItem.classList.toggle('active'); // 原有viewMessage的其他业务逻辑可在此处补充 }) </script>
内容的提问来源于stack exchange,提问作者CodeHunt
相关产品推荐
相关产品推荐

