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

标签 html css

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

这是我所拥有的:

HTML:

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

CSS:

.image {
  width: 250px;
}

.image:hover {
  background: #000000;
}

最佳答案

最简单的方法是将 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 .

关于html - 更改图像悬停时的背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17264476/

相关文章:

html - 当使用React JS在社交媒体,Gmail和Skype上共享链接时,如何为Url创建预览(图像和描述)?

html - Bootstrap 最大列宽度

javascript - 将类添加到 SVG 路径

javascript - 单击页面上的其他任何位置时,使下拉菜单返回

html - 如何在其行内垂直对齐文本? (垂直对齐不起作用)

javascript - 模态窗口位置

html - 在视口(viewport)中居中元素而不是包含 Bootstrap 列

html - 如何使子div高度与父div高度相同

CSS:右包装器从页面末尾掉落

css - 具有响应性的 CSS 中的图像优先