html - 如何为不同的文本元素(在同一类下)仅更改 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
}
解决方案
您可以使用自定义属性!在您的 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") + ")";
}
推荐阅读
- node.js - 如何通过猫鼬中的引用对象属性检索对象
- python - 当十字准线命令成功时,我的合同是否被证明是正确的?
- cloud - 互联网上的私有云服务器作为 MQTT 代理
- python - 我如何能够从列表中获取平均值并将其与总数一起打印为输出?
- python - wtforms SelectField 总是返回 None
- python - 如何在第二页上显示 Django 输入数据
- linux - 构建 libwebrtc
- android - Android/Firebase - TextView 未显示在 ListView 中
- java - 使用 touchDragged 方法后如何找出演员在 libgdx 中的新位置?
- laravel - FTP 一个 Laravel 项目