首页 > 解决方案 > 当悬停在另一个元素上时,我可以更改元素的背景颜色吗?

问题描述

是否可以通过 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>

标签: htmlcsshoverbackground-color

解决方案


使用纯 CSS:在悬停元素和目标元素之间添加一个波浪字符,以标识您希望在悬停时更改的受影响元素。In CSS, the symbol tilde(~) is know as Subsequent-sibling combinator.

MDN 通用兄弟组合器

#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>


推荐阅读