简体   繁体   中英

How do I change the colour of an element within a div on rollover using Javascript?

I have a div that has a div within it.

<div class="parent">
  <div class="child">
    Content
  </div>
</div>
<div class="parent">
  <div class="child">
    Content
  </div>
</div>
<div class="parent">
  <div class="child">
    Content
  </div>
</div>
...

I would like to change the colour of the ".child" element on hover using javascript. I have to use javascript and not jquery and not css.

Any ideas?

You need to add an eventListener to all of the children, listening forthe event mouseover .

 var children = document.getElementsByClassName("child"); for(var i=0; i<children.length; i++) { children[i].addEventListener("mouseover",function() { this.style.background = "grey"; }) } 
 <div class="parent"> <div class="child"> Content </div> </div> <div class="parent"> <div class="child"> Content </div> </div> <div class="parent"> <div class="child"> Content </div> </div> 

If you want the children to go back to white when the mouse leaves use the mouseout event with a new eventListener.

children[i].addEventListener("mouseout",function() {
   this.style.background = "white"; 
})

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