简体   繁体   中英

How do you change a color of an image entirely when hovered in <a> tag element?

I have this example code that hovers an image to change the background color. How do you fill the entire image with color when hovered?

In my code snippet, it only fills the background color of an a tag element but not the image.

Here's an image to further clarify my question.

CartIcon

How do achieve this using the hover effect in tag element.

 a img:hover { background-color: purple; } a:hover { background-color: yellow; } 
 <!DOCTYPE html> <html> <head> </head> <body> <!-- Hovered with image no text --> <a href="https://www.w3schools.com"><img src="cart.png"></a> <!-- Hovered without image just text --> <a href="http://www.wikipedia.org">Change color text</a> </p> </body> </html> 

Assuming that your image is white and the other parts are transparent. Just change the CSS like so:

 a img { background-color: purple; } a:hover img { background-color: yellow; } 
 <!DOCTYPE html> <html> <head> </head> <body> <!-- Hovered with image no text --> <a href="https://www.w3schools.com"><img src="cart.png"></a> <!-- Hovered without image just text --> <a href="http://www.wikipedia.org">Change color text</a> </p> </body> </html> 

I have found another method to change the background image. I suppose to have two images so when hovered it will change the image. Thanks for the info @Jaromanda X

 #my-img:hover { content: url('images/pinkcart.png'); } 
 <!DOCTYPE html> <html> <head> </head> <body> <img id="my-img" src="images/redcarticon.png"/> </p> </body> </html> 

And thank you also for helping me everyone.

Try with below solution with jQuery:

 a img:hover { background-color: purple; } a:hover { background-color: yellow; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <body> <!-- Hovered with image no text --> <a id='image' href="https://www.w3schools.com"><img src="cart.png"></a> <!-- Hovered without image just text --> <a id="text" href="http://www.wikipedia.org" onmouseover="$('#image').css('background-color', 'purple');" onmouseout="$('#image').css('background-color', 'white');">Change color text</a> </body> 

Please update style

a{
     padding:15px;
     background-color: purple;
     display:block;
}
a:hover {
    background-color: yellow;
}

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