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

Joh*_*ith 3 html css css3

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

这就是我所拥有的:

HTML:

<img src="http://www.floral-directory.com/flower.gif" class="image" />
Run Code Online (Sandbox Code Playgroud)

CSS:

.image {
  width: 250px;
}

.image:hover {
  background: #000000;
}
Run Code Online (Sandbox Code Playgroud)

Dav*_*mas 8

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

<span class="imgWrap">
    <img src="http://www.floral-directory.com/flower.gif" class="image" />
</span>
Run Code Online (Sandbox Code Playgroud)

并将其与CSS结合:

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

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

img:hover,
.imgWrap:hover img {
    visibility: hidden;
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.

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

.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;
}
Run Code Online (Sandbox Code Playgroud)

JS小提琴演示.