本文详解如何通过 javascript 动态管理 css 类,实现下拉菜单中“仅一个选项显示 ✓ 对勾”的单选效果:默认首项已选,点击其他项时自动移除旧对勾、添加新对勾,并同步更新按钮文本。
要实现「仅当前选中项显示对勾、其余项清除对勾」的单选交互效果,关键在于统一管理所有选项的 .checked 类状态,而非为每个元素单独绑定重复逻辑。原始代码存在两个核心问题:
在 HTML 加载完成时,为首个 元素(即 .a)添加 .checked 类,确保页面首次渲染即有对勾:
ACTIVE
? 提示:也可在 JS 中通过 document.querySelector('.a').classList.add('checked') 动态设置,增强可维护性。
使用事件委托或批量监听,确保每次点击只激活目标项、清除其余项:
window.addEventListener('click', function(event) {
// 检测是否点击了下拉菜单中的选项
if (event.target.matches('#myDropdownCity a')) {
const dropdown = document.getElementById('myDropdownCity');
const button = document.querySelector('.dropbtnCity');
const allLinks = dropdown.querySelectorAll('a'); // 获取全部选项
// 关闭下拉菜单
dropdown.classList.remove('showCity');
// 更新按钮文字
button.innerText = event.target.innerText;
// 清除所有选项的 .checked 类
allLinks.forEach(link => link.classList.remove('checked'));
// 仅为目标项添加 .checked 类
event.target.classList.add('checked');
}
});.checked::after 伪元素需满足以下条件才能正确显示:
.dropdown-contentCity a {
position: relative; /* 关键:确保 ::after 可相对定位 */
/* ... 其他原有样式 */
}
.checked::after {
content: "✓";
position: absolute;
right: 12px;
top: 50%;
transform: translateY(-50%);
color: #4CAF50;
font-weight: bold;
}function dropdownCity() {
document.getElementById("myDropdownCity").classList.toggle("showCity");
}
// 页面加载后初始化默认选中
document.addEventListener('DOMContentLoaded', () => {
const firstLink = document.querySelector('#myDropdownCity a');
if (firstLink) firstLink.classList.add('checked');
});
window.addEventListener('click', function(event) {
const target = event.target;
if (target.matches('#myDropdownCity a')) {
const dropdown = document.getElementById('myDropdownCity');
const button = document.querySelector('.dropbtnCity');
// 关闭菜单 & 更新按钮文本
dropdown.classList.remove('showCity');
button.innerText = target.innerText;
// 批量清理 + 单独激活
document.querySelectorAll('#myDropdownCity a').forEach(el =>
el.classList.toggle('checked', el === target)
);
}
});通过以上结构化处理,即可稳定实现专业级单选对勾交互——简洁、健壮、易扩展。