首页 > 解决方案 > HTML/CSS 悬停一个对象以使另一个对象更改其属性

问题描述

您好,感谢大家查看我的问题:这是我所拥有的:

#div1 {
  background: red;
  width: 200px;
  height: 200px;
}

#div2 {
  background: blue;
  width: 200px;
  height: 200px;
}
<div id="div1"></div>
<div id="div2"></div>

现在我想通过悬停 div1 将 div2 的背景更改为绿色,我该如何仅使用 css 来做到这一点?

更新:我有同样的问题,但另一个故事:

--HTML--

<div id="div1"></div>

<div id="wrapper">
<div id="div2"></div>
</div>

--HTML--

--CSS--

#div1 {
      background: red;
      width: 200px;
      height: 200px;
    }

    #div2 {
      background: blue;
      width: 200px;
      height: 200px;
    }

    #wrapper{
      width:500px;
      height:500px;
    }

--CSS--

想通了:

#div1:hover + #wrapper #div2{
background:green;}

出于某种原因,为什么 #div1:hover + #div2 不起作用

标签: htmlcss

解决方案


您可以使用+css 选择器来执行此操作,该选择器直接在当前元素之后选择元素

div {
  height: 50px;
  width: 50px;
  border: 1px solid black;
}

#div1:hover+#div2 {
  background-color: green;
}
<div id="div1"></div>
<div id="div2"></div>


推荐阅读