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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17264476/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 10:23:38  来源:igfitidea点击:

Change background color on image hover

htmlcss

提问by John Smith

How would I make it so that if you hover over an image, the entire image changes to the color black (the image link must be in the HTML tag as the sizes and images are different)?

我将如何做到这一点,如果您将鼠标悬停在图像上,整个图像会变为黑色(图像链接必须在 HTML 标记中,因为大小和图像不同)?

Here's what I have:

这是我所拥有的:

HTML:

HTML:

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

CSS:

CSS:

.image {
  width: 250px;
}

.image:hover {
  background: #000000;
}

回答by David says reinstate Monica

The easiest way to do this is to wrap the imgelement in another, for example a span:

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

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

And couple that to the CSS:

并将其与 CSS 结合起来:

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

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

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

JS Fiddle demo.

JS小提琴演示

And, if you'd like to make it a little prettier, using transitions to fade in/out:

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

.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.

JS小提琴演示

回答by rsm23

The HTML

HTML

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

The CSS

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;
}

Live Example @ http://cdpn.io/Bmthc

现场示例@ http://cdpn.io/Bmthc