当鼠标悬停在图像上时更改div的背景图像

3

我有以下代码:

<!DOCTYPE html> <html >
 <head> 
    <style type="text/css"> 
        .imgBox {background: url(lock75.png) no-repeat; } 
        .imgBox:hover {background: url(lock75light.png) no-repeat; } 
    </style> 
</head> 
<body> 
    <div style="width:200px; height:200px; border:1px solid;" class="imgBox"> </div> 
</body>
</html> 

我的图片尺寸为75x75,当我悬停在边框上时,出现了问题,图片会发生改变,我希望在悬停在图片上时改变图片。
注意:我需要一个类似于这个的HTML结构。
编辑:我忘记提到了,我需要把图片居中放置在其他div上方,但没有固定的空间来放置图片。
谢谢。

div的宽度减小为75px。 - Adam Azad
类似于哪一个? - Guruprasad J Rao
不可能,我在div中还有其他内容,除了图片。 - MartinZPetrov
你需要为图片创建一个额外的div。 - Adam Azad
@AdamAzad 请再详细说明一下您的想法?我有内容(其他div按钮等)。您是指将其他div放置在我的div上方,并使用z-index吗? - MartinZPetrov
看看我创建的这个fiddle:http://jsfiddle.net/aoe1e8r0/ - Adam Azad
2个回答

1
我认为您正在搜索这个:

我认为您正在搜索这个:

.container {
    border:1px solid #000;
    display:inline-block;
    height:200px;
    width:200px;
}
.imgBox {
    background:url(http://placehold.it/100x100) no-repeat;
    height:75px;
    width:75px;
} 
.imgBox:hover {
    background:url(http://placehold.it/75x75) no-repeat;
}
<div class="container">
    <div class="imgBox"> </div> 
</div>


我忘了提到我需要将图片居中放置在其他div上方,而我没有为图片指定特定的空间。 - MartinZPetrov

1
你需要一个容器,可以在以下结构中同时容纳背景图片和内容(我知道你要求与你发布的类似,但这是不可能的;好吧,它是可能的,但它将涉及CSS3元素和jQuery)。
这是设置:

body {
    padding:10px;
}
.img-box {
    max-width:200px;
    width:100%;
    border:1px solid #ddd;
}
.img-box .img {
    width:200px;
    height:200px;
    background: url(https://unsplash.it/200/200/?image=876) no-repeat;
    border-bottom:1px solid #ddd;
}
.img-box .img:hover {
    background: url(https://unsplash.it/200/200/?image=876&blur) no-repeat;
}
p { margin:5px } 
<div class="img-box">
    <div class="img" ></div>
    <p>other content here</p>
</div>


我忘了提到我需要将图片居中放置在其他div上方,而我没有为图片指定特定的空间。 - MartinZPetrov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接