简体   繁体   中英

ton>Hover over an <a> tag to change a button color inside the <a> tag

My webpage is constructed as:

   <a class="hoverMe" href="">   
      <div class="somediv1">
         <div class="somediv2">
           <div class="somediv3">
              <button class="changeColor"></button>
           </div>
          </div>   
      </div>
   </a> 


   <a class="hoverMe" href="">   
      <div class="somediv1">
         <div class="somediv2">
           <div class="somediv3">
              <button class="changeColor"></button>
           </div>
          </div>   
      </div>
   </a> 

I want to be able to change the color of the button inside the particular <a> </a> that's being hovered over. How should I write the javascript to do it? Thanks so much for the help!

First at all, you only need a button to fire an JS onclick event. In every other case you use a div to style a "button". Also a button is not an empty tag and therefor needs a closing tag <button>Text</button>

Just like this:

 a { text-decoration: none; color: black; } a div { border: 1px solid black; width: min-content; white-space: nowrap; padding: 5px; }
 <a href=""><div>I'm a Link-Button</div></a>

to change the color during hover, you dont need JS. You can simply use the :hover pseudo selector like this:

 a { text-decoration: none; color: black; } a div { border: 1px solid black; width: min-content; white-space: nowrap; padding: 5px; } a:hover div { background-color: red; }
 <a href=""><div>I'm a Link-Button</div></a>

As you insist on using your invalid HTML and seem not to understand the use of:hover the same for your code:

 .hoverMe:hover.changeColor { background-color: red; }
 <a class="hoverMe" href=""> <div class="somediv1"> <div class="somediv2"> <div class="somediv3"> <button class="changeColor">Button 1</button> </div> </div> </div> </a> <a class="hoverMe" href=""> <div class="somediv1"> <div class="somediv2"> <div class="somediv3"> <button class="changeColor">Button 2</button> </div> </div> </div> </a>

This is a pretty basic question checking docs usually can help you. Check this out

The use of :hover pseudo selector will help you achieve what you want. In our example we see the a:hover action which enables the hover color change.

 a:hover { background-color: yellow; } a { font: bold 11px Arial; text-decoration: none; background-color: #EEEEEE; color: #333333; padding: 2px 6px 2px 6px; border-top: 1px solid #CCCCCC; border-right: 1px solid #333333; border-bottom: 1px solid #333333; border-left: 1px solid #CCCCCC; }
 <a href="https://www.w3schools.com">w3schools.com</a> <a href="https://www.wikipedia.org">wikipedia.org</a> <p><b>Note:</b> The:hover selector style links on mouse-over.</p>

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