html - 当悬停在另一个元素上时,我可以更改元素的背景颜色吗?
问题描述
是否可以通过 CSS 将鼠标悬停在辅助元素上时更改元素的背景。我想让代码尽可能简单。
我希望让 'sup-background' 元素仅在 :hover 时改变颜色。我知道下面的代码只会改变文本元素的背景颜色。
任何建议或答案都会很棒,谢谢。
<!doctype html>
<html>
<style>
a {
font-size: 12px;
}
sup {
font-size: 10px;
}
.sup-background {
padding: 10px;
border-radius: 100px;
background-color: white
}
a:hover+.sup-background {
background-color: red;
}
</style>
<body>
<div><a>Hello</a><sup class="sup-background">YOU</sup></div>
</body>
</html>
解决方案
使用纯 CSS:在悬停元素和目标元素之间添加一个波浪字符,以标识您希望在悬停时更改的受影响元素。In CSS, the symbol tilde(~) is know as Subsequent-sibling combinator
.
#cont {
display: flex;
justify-content: space-around;
}
.el1 {
height: 200px;
width: 200px;
background: #eee;
}
.el2 {
height: 200px;
width: 200px;
background: #ff0;
}
.el1:hover~.el2 {
background: #f00;
color: #fff;
}
<div id="cont">
<div class="el1"></div>
<div class="el2"></div>
</div>
这也可以通过 Javascript 使用包含两个事件侦听器的函数来实现;一个改变背景mouseover
,另一个改变背景mouseout
。
let el1 = document.getElementById('el-1');
let el2 = document.getElementById('el-2');
// make a function that adds two eventlisteners
// with two elements passed as params into the function
// paramater 1 (e) is the hover element
// parament 2 (el) is the affected element
const hoverEvent = (e,el) => {
e.addEventListener('mouseover', () => {
el.style.background = "#FF0";
})
e.addEventListener('mouseout', () => {
el.style.background = "#F00";
})
}
// add the two parameters (elements) defined above tot he function
hoverEvent(el1, el2);
#cont {
display: flex;
justify-content: space-around;
}
#el-1 {
background: #ccc;
width: 200px;
height: 200px;
}
#el-2 {
background: #f00;
width: 200px;
height: 200px;
}
<div id="cont">
<div id="el-1"></div>
<div id="el-2"></div>
</div>
推荐阅读
- virtual-machine - 我尝试在 VirtualBox 中安装 Arista vEOS,但出现此错误:“未找到启动配置”
- java - 推土机:成功转换后用源值覆盖的字段
- sql - 获取具有最大值的行的最有效方法是什么?
- python - UDP 客户端/服务器类型错误
- javascript - Vue 组件默认数据值覆盖了我在 beforeRouteUpdate 中设置的值
- javascript - 如何调整 Idea Intellij Ultimate 使其不会在 16GB 主机上崩溃?
- python - 如何在情节中添加标签?
- c# - C#:从调用堆栈中读取特定类型的最后一个自定义属性
- sequelize.js - Sequelize:如果声明不是基于 PK 并且适用于 PK 搜索,getOne() 将抛出“字段列表中的未知列 (...)”
- typescript - 扩展派生类中的参数类型