【问题标题】:How can I change the color of the places I want when the li element hover?当 li 元素悬停时,如何更改我想要的地方的颜色?
【发布时间】:2021-07-03 06:00:18
【问题描述】:

我有如下的 css 和 html 代码。

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  list-style-type: none;
}

.container {
  width: 1000px;
  margin: 0 auto;
}

.top-content {
  width: 100%;
  height: 100px;
  background-color: gray;
}

nav ul {
  display: flex;
  justify-content: space-around;
}

nav ul li:hover {
  cursor: pointer;
  color: red;
}

main {
  width: 100%;
  height: 500px;
  background: green;
}

nav ul li:hover .top-content {
  background: red;
}

nav ul li:hover main {
  background: red;
}
<div class="container">
  <div class="top-content"></div>

  <nav>
    <ul>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
    </ul>
  </nav>

  <main></main>
</div>

当我将鼠标悬停在 li 元素上时,我想要将 .top-content 类和 main 元素涂成红色。但据我了解,我的选择器有问题。如何仅使用 css 更改这些元素的颜色?

【问题讨论】:

  • 你能改变你的html结构吗?如果不是,你不能只在 Css 中做到这一点
  • 你能举个例子吗?

标签: html css


【解决方案1】:

CSS 属性只能修改元素及其子元素(它们无法访问父元素或兄弟元素)。 更多信息 here

您需要借助 JavaScript 来实现这一点。

let lis = document.querySelectorAll("nav ul li");
let topContent = document.querySelector(".top-content"); 

let main = document.querySelector("main"); 

lis.forEach(li=>{
  li.onmouseover = ()=>{
    topContent.style.background = "red";
    main.style.background = "red";
  }
  li.onmouseleave = ()=>{
    topContent.style.background = "gray";
    main.style.background = "green";
  }
  
})
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

ul {
  list-style-type: none;
}

.container {
  width: 1000px;
  margin: 0 auto;
}

.top-content {
  width: 100%;
  height: 100px;
  background-color: gray;
}

nav ul {
  display: flex;
  justify-content: space-around;
}

nav ul li:hover {
  cursor: pointer;
  color: red;
}

main {
  width: 100%;
  height: 500px;
  background: green;
}
<div class="container">
  <div class="top-content"></div>

  <nav>
    <ul>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
      <li>Lorem</li>
    </ul>
  </nav>

  <main></main>
</div>

【讨论】:

  • 感谢您的回答。实际上,我想做的是在 li 元素处于悬停状态时为这些字段添加覆盖。我想我不能,再次感谢你。
  • 欢迎。您要添加什么样的叠加层?只是问问。
猜你喜欢
  • 1970-01-01
  • 2013-02-26
  • 1970-01-01
  • 2017-07-03
  • 1970-01-01
  • 2014-10-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多