更改图像悬停时的背景颜色

时间:2013-06-23 19:30:17

标签: html css css3

如何将其悬停在图像上,整个图像会变为黑色(图像链接必须位于HTML标记中,因为尺寸和图像不同)?

这就是我所拥有的:

HTML:

<img src="http://www.floral-directory.com/flower.gif" class="image" />

CSS:

.image {
  width: 250px;
}

.image:hover {
  background: #000000;
}

2 个答案:

答案 0 :(得分:8)

最简单的方法是将img元素包装在另一个元素中,例如span

<span class="imgWrap">
    <img src="http://www.floral-directory.com/flower.gif" class="image" />
</span>

将它与CSS相结合:

.imgWrap {
    display: inline-block;
    border: 1px solid #000;
}

.imgWrap:hover {
    background-color: #000;
}

img:hover,
.imgWrap:hover img {
    visibility: hidden;
}

JS Fiddle demo

并且,如果你想让它变得更漂亮一点,使用过渡淡入/淡出:

.imgWrap {
    display: inline-block;
    border: 1px solid #000;
    background-color: #fff;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -webkit-transition: all 1s linear;
    transition: all 1s linear;
}

.imgWrap img {
    opacity: 1;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -webkit-transition: all 1s linear;
    transition: all 1s linear;
}

.imgWrap:hover {
    background-color: #000;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -webkit-transition: all 1s linear;
    transition: all 1s linear;
}

img:hover,
.imgWrap:hover img {
    opacity: 0;
    -moz-transition: all 1s linear;
    -ms-transition: all 1s linear;
    -o-transition: all 1s linear;
    -webkit-transition: all 1s linear;
    transition: all 1s linear;
}

JS Fiddle demo

答案 1 :(得分:0)

HTML

<div class="change_bg">
  <img src="http://eofdreams.com/data_images/dreams/image/image-07.jpg" >
</div>

CSS

.change_bg img{
    max-width : 300px;
}

.change_bg{
    width : 300px;
    height : 300px;
    float:left;
}

.change_bg img:hover{
    visibility : hidden;
}

.change_bg:hover {
    background : #bc7d89;
}

实例@ http://cdpn.io/Bmthc