简体   繁体   English

将鼠标悬停在div上时会显示其他图像

[英]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: 基本上,我想要的是将图像悬停在img所在的图像的“ div”(框)上时进行更改。请看一下代码:

<!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. 您也没有指定要分配URL的src。 You would need to use this.src='URL' in the onmouseover and onmouseout events. 您需要在onmouseover和onmouseout事件中使用this.src='URL'

Here is a link about the this keyword: How does the "this" keyword work? 这是有关this关键字的链接: “ this”关键字如何工作?

Try with this.src : 试试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 . 您可以将图像放在div的背景中。

DEMO 演示

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

More on CSS background 有关CSS背景的更多信息

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM