search

Home  >  Q&A  >  body text

Dynamically add :hover effects to multiple elements

<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粉203792468P粉203792468468 days ago488

reply all(1)I'll reply

  • P粉564192131

    P粉5641921312023-08-16 12:53:06

    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');
      });
    });

    reply
    0
  • Cancelreply