使用原生js实现以下效果:点击容器内的图标,图标边框变成border:1px solid red,点击空白处重置
参考答案
const box = document.getElementById('box');
document.addEventListener('click', (e) => {
const icon = e.target.closest('.icon');
box.querySelectorAll('.icon').forEach(i => i.style.border = '');
if (icon) icon.style.border = '1px solid red';
});
要点
- 用事件委托在 document 上监听,统一处理
closest兼容点到子节点的情形- 先重置全部再设置当前,天然实现"点空白重置"
- 若点击图标时不想冒泡到 document 重置,需
e.stopPropagation()或调整判定顺序