首页 > 解决方案 > 如何为不同的文本元素(在同一类下)仅更改 CSS 类的一部分?

问题描述

摘要:在我的代码中,当将鼠标悬停在文本元素上时,下方会出现一个图像。我想对其他文本元素执行此操作,而我唯一要更改的是图像 url。但是,我不想制作一个全新的 item:hover 类来更改悬停后出现的图像的 url。有没有办法解决这个问题?

我有两个样式相同的项目。

<h6 class = "item"> felucian garden spread </h6>
<h6 class = "item"> yobshrimp noodle salad </h6>

当悬停在“项目”上时,我下面的 CSS 会显示一个图像。但是,当悬停在“yobshrimp 面条沙拉”上时,我希望出现不同的图像。有没有办法做到这一点,即使他们在同一个班级?我试图避免为每个菜单项创建一个新的类和悬停事件。

.item:hover:after {
  content: "";
  background-image:url(felucian.jpg); // <- i want to change this part *only* for a different text, "yobshrimp noodle salad"
  background-size: 100% 100%;
  margin-left: 30%;
  display: block;
  height: 266px;
  width: 437px;
  -webkit-animation: fade-in-top 0.6s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
            animation: fade-in-top 0.6s cubic-bezier(0.390, 0.575, 0.565, 1.000) both;
  left: 150px;
  top: 50px;
  transition: all ease-in-out 1s
}

标签: htmlcss

解决方案


您可以使用自定义属性!在您的 HTML 中:

<h6 class="item" data-hover-image="felucian.jpg">felucian garden spread</h6>
<h6 class="item" data-hover-image="yobshrimp.jpg">yobshrimp noodle salad</h6>

在 CSS 中:

.item :hover :after {
  ...
  background-image: attr(data-hover-image url); 
}

关于attr()阅读这里

编辑:

由于不是很多浏览器支持自定义属性,您可以使用 javascript 遍历所有.item元素并更改它们的 url。例如:

const items = document.getElementsByClassName("item");
for(const item of items) {
  item.style.backgroundImage =
    "url(" + item.getAttribute("data-hover-image") + ")";
}

推荐阅读