简体   繁体   中英

Make a different image appear when hovering over a div

I've tried many methods on how to resolve this issue, but I can't seem to find a solution, so it's time to ask help from more experienced people. Basically what I want is for an image to change when I hover over its 'div' (the box) that the img is in. Have a look at the code:

<!DOCTYPE html>
<html>
    <head>
        <style>

            body {
            background: grey;
            }

            #box {
                margin: 0 auto;
                width:  300px;
                height: 300px;
                background: blue
            }
            #box img {
                display: block;
                margin: 0 auto;
                padding-top: 75px;
            }
        </style>
        <meta charset="utf-8">
    </head>
    <body>
        <a href="#">
            <div id="box">
                <img src="registration_icon_white.png" onmouseover="src='registration_icon_black.png'" onmouseout="'registration_icon_black.png'">
            </div>
        </a>
    </body>

(the images are the same, just with different colors)

Any help would be appreciated, thanks.

You're not specifying what src to are assigning the URL too. You would need to use this.src='URL' in the onmouseover and onmouseout events.

Here is a link about the this keyword: How does the "this" keyword work?

Try with this.src :

    <div id="box">              
      <img title="some title" src="registration_icon_white.png" 
           onmouseover="this.src='registration_icon_black.png'"
           onmouseout="this.src='registration_icon_white.png'">
    </div>

You can just put the image in the background of the div .

DEMO

<div id="box"></div>

More on CSS background

#box {
  background: url("registration_icon_black.png");
  height: 500px;
}

#box:hover{
  background: url("registration_icon_white.png");
}

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