本文介绍如何通过 javascript 动态管理 css 类,实现下拉列表中仅在当前选中项显示对勾符号(✓),其余项自动清除该标记,并确保首次加载时默认高亮第一个选项。
要实现“单选式对勾标记”效果——即点击某一项时,仅该项显示 ✓,其余所有项的 ✓ 消失——关键在于统一管理所有可选项的 .checked 类状态,而非为每个元素单独绑定重复逻辑。
原代码存在多个问题:
✅ 正确做法是:
以下是优化后的完整实现:
ACTIVE ONETWO THREE
function dropdownCity() {
document.getElementById("myDropdownCity").classList.toggle("showCity");
}
// 页面加载后初始化:确保首个选项已标记,按钮文本同步
document.addEventListener('DOMContentLoaded', () => {
const dropdown = document.getElementById('myDropdownCity');
const firstLink = dropdown.querySelector('a');
const dropbtn = document.querySelector('.dropbtnCity');
if (firstLink && !firstLink.classList.contains('checked')) {
firstLink.classList.add('checked');
}
dropbtn.textContent = firstLink?.textContent || 'ACTIVE';
});
// 使用事件委托,避免重复绑定 —— 推荐方式
document.addEventListener('click', function(event) {
const target = event.target;
if (target.matches('#myDropdownCity a')) {
event.preventDefault(); // 防止跳转锚点
const dropdown = document.getElementById('myDropdownCity');
const dropbtn = document.querySelector('.dropbtnCity');
// 清除所有 checked
dropdown.querySelectorAll('a').forEach(el => el.classList.remove('checked'));
// 为当前项添加 checked
target.classList.add('checked');
// 更新按钮文字
dropbtn.textContent = target.textContent;
// 关闭下拉菜单
dropdown.classList.remove('showCity');
}
});? CSS 注意事项:
确保 .checked::after 的样式能正确渲染(注意伪元素需配合 position: relative 或调整 margin-top 以对齐):
.dropdown-contentCity a.checked::after {
content: "✓";
margin-left: 8px; /* 推荐用 margin-left 替代 flex 布局,更稳定 */
color: #2E7D32;
font-weight: bold;
}✅ 优势总结:
按此方案实施后,即可实现专业、健壮的单选对勾交互体验。