简体   繁体   中英

How to make an onclick event active on all child elements

Right now I have a large div with multiple sub elements inside of it. I have attached an onclick event to the large div tag. However, the onclick event only works when you click on empty space inside of the large div. It does not work when you click on child elements such as text inside of the large div. I am wondering if there is an easy way to capture any clicks inside of the large div, so I do not need to attach the onclick event to every child element.

EDIT: Add code snippet

Try to change text from blue to red. When you click on the empty space of the larger div, the text changes color. When you click on the child elements(the text), the color does not change. Is there an easy fix to be able to click anywhere inside of the large div to change the text color.

 function changeToRed() { event.target.querySelector('.change').style.color = "red"; }
 .change { color: blue; }
 <div onclick="changeToRed()"> <p class="change">Change text color</p> <p> Another Paragraph</p> </div>

您可以在现有元素上使用叠加元素,并使用 css 使其透明,并在此叠加元素上添加事件侦听器!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM