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

鼠标悬停容器显示图片功能失效,求排查问题原因

问题:鼠标悬停容器时无法显示图片

我编写了一段代码,期望鼠标悬停在容器上时显示图片,但该功能完全没有效果。请问问题出在哪里?

原代码

HTML

<div class=“hover-container”>Hover over me to see an image</div>

CSS

.hover-container {
  position: relative;
  display: inline-block;
  font-size: 24px;
  font-weight: bold;
  color: white;
  padding: 10px 20px;
  background-color: black;
  transition: background 0.3s ease;
}

/* 默认背景 */
.hover-container::before {
  content: “”; 
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  z-index: -1;
  transition: opacity 0.3s ease;
  opacity: 1;
}

/* 悬停时显示图片背景 */
.hover-container:hover::before {
  background-image: url('https://plus.unsplash.com/premium_photo-1683535508528-9228dcc8fa4c?q=80&w=2071&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');
  background-size: cover;
  background-position: center;
  opacity: 1;
}

问题原因

  1. 中文引号语法错误:HTML中的class=“hover-container”和CSS中的content: “”;使用了中文双引号,浏览器无法识别正确的类名和伪元素内容,直接导致样式失效。
  2. 背景层级遮挡:.hover-container自身设置了background-color: black,而伪元素的z-index: -1处于容器背景的下方,即使伪元素加载了图片,也会被容器的黑色背景完全挡住。

修复后的代码

HTML

<div class="hover-container">Hover over me to see an image</div>

CSS

.hover-container {
  position: relative;
  display: inline-block;
  font-size: 24px;
  font-weight: bold;
  color: white;
  padding: 10px 20px;
  transition: background 0.3s ease;
}

.hover-container::before {
  content: ""; 
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: black;
  z-index: -1;
  transition: opacity 0.3s ease;
}

.hover-container:hover::before {
  background-image: url('https://plus.unsplash.com/premium_photo-1683535508528-9228dcc8fa4c?q=80&w=2071&auto=format&fit=crop&ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D');
  background-size: cover;
  background-position: center;
}

修复说明

  • 将所有中文双引号替换为英文双引号,确保浏览器能正确解析类名和伪元素的content属性。
  • 移除.hover-container自身的background-color: black,让伪元素的背景(默认黑色、hover时图片)能正常显示,不再被遮挡。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.13 11:09:54