Dynamically add :hover effects to multiple elements
P粉203792468
2023-08-15 23:49:58
<p>Is it possible to programmatically add a <code>hover</code> effect to multiple elements? In our system, where there are multiple elements that represent a single unit (but need to be separated into multiple elements for other reasons), in some cases they should be recolored together on hover. Is it possible to programmatically add a <code>hover</code> effect to multiple elements? Or is this a good practice? </p>
<p>I was able to solve this problem by using <code>my_own_css_class</code> to add it to all elements on hover. But I feel like it might be of some benefit to me to programmatically make them have a <code>hover</code> effect (e.g. I want the hover effect to clear when the mouse leaves them, etc.). </p>
I'm not sure if I understand the question correctly, but as far as I know there are two possible solutions and they both involve using 'my_own_css_class'
.hoverable-element { /* 无 */ } .hoverable-element:hover { /* 重新着色 */ }.hoverable-element-js { /* 无 */ } .hover-effect-js { /* 重新着色 */ }const elements = document.querySelectorAll('.hoverable-element-js'); elements.forEach(element => { element.addEventListener('mouseover', () => { element.classList.add('hover-effect-js'); }); element.addEventListener('mouseout', () => { element.classList.remove('hover-effect-js'); }); });