通过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>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句