Dynamically add :hover effects to multiple elements
P粉203792468
P粉203792468 2023-08-15 23:49:58
0
1
429
<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>
P粉203792468
P粉203792468

reply all(1)
P粉564192131

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'

  1. CSS method
<div class="hoverable-element">元素1</div>
<div class="hoverable-element">元素2</div>
<div class="hoverable-element">元素3</div>
.hoverable-element {
  /* 无 */
}

.hoverable-element:hover {
  /* 重新着色 */
}
  1. JavaScriptMethod
<div class="hoverable-element-js">元素1</div>
<div class="hoverable-element-js">元素2</div>
<div class="hoverable-element-js">元素3</div>
.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');
  });
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!