【问题标题】:Hover on div affects outside element [duplicate]悬停在div上会影响外部元素[重复]
【发布时间】:2018-02-28 05:29:25
【问题描述】:

我试图在 div 悬停时影响外部元素。像这样的:

<div class="affected">
  Hi
</div>

<div>
  <div class="hover-me"></div>
</div>

CSS:

.hover-me:hover ~ .affected {
  color: 
}

我尝试过使用其他同级选择器,但它不起作用。

【问题讨论】:

  • CSS 以自上而下的方式工作。您可以定位结构中的下一个相邻兄弟,但不能定位之前的兄弟。
  • CSS 无法选择其上一个元素。它只能选择它的下一个兄弟,或者我们可以使用悬停在父元素上来实现。
  • 所以我需要使用jQuery来实现这个,对吧?
  • @EbenizerPinedo 是的,使用 jQuery 就可以实现。如果您需要帮助,请尽管询问。
  • 我想我已经有了,谢谢 ;)

标签: css hover


【解决方案1】:

使用纯 CSS 会变得非常棘手。

一种方法,如果您不需要包含可悬停子项的 div 上的指针事件(悬停、点击等),将容器设置为可操作 div,禁用指针事件,在孩子上重置它们,并使用某种魔法使兄弟姐妹在您的 HTML 上以相反的顺序排列,这样它们就可以用兄弟姐妹选择器作为目标(因为您不能定位以前的兄弟姐妹)

有点像

body{
  /*switches the oder of .affected and .hover-container, so .affected can be bellow in the HTML and be targeted with sibling selectors, while showing above*/
  display:flex;
  flex-direction:column-reverse;
}

.hover-container:hover ~ .affected{
/*targets the action on the container*/
  background:red;
}

.hover-container{
/*disables pointer-events on the container, so entering it won't cause the hover effect on the sibling*/
  pointer-events:none;
}

.hover-me{
/*resets pointer-events on the .hover-me child, so the previous :hover we set for the container will work only when hovering this child*/
  pointer-events:auto;
  cursor:pointer;
}

div{
  border:2px solid grey;
  margin:20px 40px;
  text-align:center;
}
<div class="hover-container">
  this is the hover container
  <div class="hover-me">hover me</div>
</div>

<div class="affected">
  affected
</div>

但这可能是一种不太常见的情况,到那时你最好使用 JS 方法。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-01-15
    • 2013-08-01
    • 2019-05-12
    • 2020-02-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多