You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现鼠标悬停div时移除其内部图片的灰度效果

实现方案

你需要给包含图片的外层div添加:hover伪类选择器,匹配其内部的图片元素,覆盖灰度滤镜属性即可实现需求,还可以额外加过渡属性让切换效果更自然。

修改后的完整代码如下:

<div class="example">
 <div class="a">
  <img src="https://sep.yimg.com/ay/filmandvideolighting/times-square-106-primary-red-lighting-gel-sheet-10x10-in-1.jpg" class="one" width="60" />
 </div>
 <div class="b">
  <img src="https://sep.yimg.com/ay/filmandvideolighting/times-square-106-primary-red-lighting-gel-sheet-10x10-in-1.jpg" class="two" width="60" />
 </div>
</div>

<style>
.one, .two {
  -webkit-filter: grayscale(100%); /* Safari 6.0 - 9.0 */
  filter: grayscale(100%);
  margin-left: 19px;
  padding-top: 10px;
  padding-bottom: 10px;
  /* 全局加过渡,切换更顺滑 */
  transition: filter 0.3s ease;
  -webkit-transition: -webkit-filter 0.3s ease;
}

.two {
  padding-top: 10px;
}

.one {
  padding-bottom: 5px;
}

.example {
  width: 100px;
  background-color: black;
  position: absolute;
  top: 0;
  left: 0;
}

.a {
  outline: 1px solid white;
}

/* 新增悬停样式:父div悬停时,内部图片灰度清零 */
.a:hover .one, .b:hover .two {
  -webkit-filter: grayscale(0);
  filter: grayscale(0);
}
</style>

如果后续要给更多同类div加这个效果,直接给这类包含图片的div统一个类名,比如.item,然后统一写.item:hover img {filter: grayscale(0);}即可,不需要逐个写类名。

内容的提问来源于stack exchange,提问作者Anonymous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 05:24:04