将鼠标悬停在div上会影响外部元素 [英] Hover on div affects outside element

查看:38
本文介绍了将鼠标悬停在div上会影响外部元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当div悬停时,我试图影响一个外部元素.像这样:

I'm trying to affect an outside element when a div is hovered. Something like this:

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

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

CSS:

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

我尝试了其他同级选择器,但是它不起作用.

I've tried with other sibling selectors but it doesn't work.

推荐答案

使用纯CSS会变得很棘手.

With pure CSS that's gonna be as tricky as it gets.

一种方法, IF ,在包含可悬停子项的div上不需要指针事件(悬停,单击等),将容器设置为可操作的div,禁用指针事件,将它们重置在孩子身上,并使用某种魔术使它们在HTML上具有相反的顺序,以便可以使用同级选择器将它们定位(因为您无法定位以前的同级)

An approach, IF you don't need pointer-events (hover, clicks, etc) on the div that contains the hoverable child, is setting the container as actionable div, disabling pointer-events, resetting them on the child, and using some sort of magic to have the siblings in reverse order on your HTML so they can be targeted with sibling selectors (as you cannot target previous siblings)

类似

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方法会更好.

But that's probably a not so common scenario, at that point you'll be better off with a JS approach.

这篇关于将鼠标悬停在div上会影响外部元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆