1 回答
TA贡献1818条经验 获得超11个赞
使用最近容器中的委托来选择单击该容器中的任何内容
window.addEventListener("load", function() { // when the page has loaded
document.getElementById("container").addEventListener("click", function(e) {
[...this.querySelectorAll("div")] // the "this" is the container
.forEach(div => div.classList.add('contorno'));
});
});
* {
box-sizing: border-box;
}
body {
background-color: antiquewhite;
}
#rosso {
width: 25%;
height: 150px;
background-color: red;
display: inline-block;
}
#blu {
width: 25%;
height: 150px;
background-color: blue;
display: inline-block;
}
#giallo {
width: 25%;
height: 150px;
background-color: yellow;
display: inline-block;
}
.contorno {
border: 8px solid black;
}
<div id="container">
<div id="rosso"></div>
<div id="blu"></div>
<div id="giallo"></div>
</div>
如果您只想单击 div,请执行以下操作
window.addEventListener("load", function() { // when the page has loaded
document.getElementById("container").addEventListener("click", function(e) {
if (e.target.tagName === "DIV") { // only if we click a div in the container
[...this.querySelectorAll("div")] // the "this" is the container
.forEach(div => div.classList.add('contorno'));
}
});
});
* {
box-sizing: border-box;
}
body {
background-color: antiquewhite;
}
#rosso {
width: 25%;
height: 150px;
background-color: red;
display: inline-block;
}
#blu {
width: 25%;
height: 150px;
background-color: blue;
display: inline-block;
}
#giallo {
width: 25%;
height: 150px;
background-color: yellow;
display: inline-block;
}
.contorno {
border: 8px solid black;
}
<div id="container">
<div id="rosso"></div>
<div id="blu"></div>
<div id="giallo"></div>
</div>
添加回答
举报