html, div, css - hover action and background image

2019-07-16 14:41发布

#logo
{
    position: relative;
    width: 100px;
    height: 18px;
    float: right;

    background-image: url('../images/logo_def.png');
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

#logo a:hover
{
    background-image: url(../images/logo_h.png);
} 

It works, but bg-image doesn't change when mouse is over it, why?

6条回答
淡お忘
2楼-- · 2019-07-16 15:11

The background-image is originally assigned to #logo. On a:hover the ANCHOR'S background-image is changed. Thus the following would work:

#logo a
{
    position: relative;
    width: 100px;
    height: 18px;
    float: right;

    background-image: url('../images/logo_def.png');
    background-repeat: no-repeat;
    background-position: 50% 50%;
}

#logo a:hover
{
    background-image: url(../images/logo_h.png);
}
查看更多
爷、活的狠高调
3楼-- · 2019-07-16 15:13

You've applied the hover image to an <a> element. There is no <a> element in your inside your div#logo.

查看更多
劳资没心,怎么记你
4楼-- · 2019-07-16 15:21

Wouldn't it be simpler to use onMouseOver and onMouseOut javascript functions?

<script type="text/javascript">
function divcolor(){ document.getElementById('div1').style.background='#FFDFA3'; }
function divcolor2(){ document.getElementById('div1').style.background='#FFFFFF'; }
</script>

<div id="div1" onmouseover="divcolor();" onmouseout="divcolor2();">Hover ME and I will highlight for you :)</div>

I used background colors, but the same should work with images.

查看更多
戒情不戒烟
5楼-- · 2019-07-16 15:24

It should be noted that you shouldn't put block level elements inside an anchor, which is an inline element that you can set to display block. The correct hierarchy should be something like div#footer > a > span#logo with the corresponding css.

查看更多
ゆ 、 Hurt°
6楼-- · 2019-07-16 15:32

Well, the immediate problem is that there's no <a> element inside #logo. Changing your second rule to target the correct element will "fix" this problem:

#footer a:hover
{
    background-image: url(../images/logo_h.png);
}

Edit:
As was pointed out in the comments:

The style of the first rule should be applied to the A element and the #logo DIV should be removed since it serves no purpose whatsoever.

This is indeed the better fix for your problem, as it will reduce clutter and help prevent further headaches in the future. (thanks to @Julian for the clarification)

查看更多
我欲成王,谁敢阻挡
7楼-- · 2019-07-16 15:33

You could style your div to have an anchor element and then use a:hover:

<div id="blah">
<p> <a href="#"></a></p>
</div>

Then your CSS

#blah a:hover {
 background-image: url(myImage.jpg);
}
查看更多
登录 后发表回答