CSS-悬停通过元素来激活在被覆盖的元素上悬停

我有一个页面布局涉及很多位置绝对和 z 索引,所以有很多元素是相互重叠的。

其中一个元素只包含文本,它悬浮在许多其他东西的顶部。

在该元素下面有几个应用了 CSS 悬停伪类的元素。

当鼠标经过包含文本的元素时,我希望下面的 Element 以某种方式响应鼠标的存在并激活伪类样式。

有没有什么方法可以设计一个元素的样式,让鼠标悬停可以通过它传递到底下的任何元素?

对于 JavaScript 来说,这不会太难,但是为了尽可能简单,我现在不想走这条路。以后我会用 JavaScript 把事情搞得更复杂。

谢谢

另外,我已经在使用 HTML5和 CSS3了,所以使用这些新标准的解决方案没有任何问题。

61709 次浏览

you can use pointer-events: none; to the element on top:

div {
width   : 200px;
height  : 200px;
float   : left;
cursor  : pointer;
border  : 1px green solid;
}


div + div:hover { background: #a1a6c8; }


div:first-child {
pointer-events : none;
position       : absolute;
top            : 100px;
left           : 100px;
border         : 1px green solid;
background     : #c1c6c8;
}
  <div> on top of all: hover me </div>
<div>1</div>
<div>2</div>
<div>3</div>
<div>4</div>
<div>5</div>
<div>6</div>




as you can see, when you hover the element on the top the element behind is activated. For more info about this property: https://developer.mozilla.org/en/CSS/pointer-events

Also, something that people may find useful is that you can re-enable pointer events on child elements of the pointer-events:none element by setting them to pointer-events:auto explicitly. This doesn't seem to be well documented and turns out to be very useful. – slicedtoad

@slicedtoad's comment was hugely useful for me, so I think it deserves a full answer. If you set pointer-events: none to a parent, you'll disable the events for it's children. HOWEVER, if you set point-events: auto to the children, they will work again.

This also works when the children have a negative z-index, and therefore become unresponsive to pointer-events.

This is a Javascript solution which the question doesn't call for, but this page is connected to this sort of hover problem search query:

I have a case where this arrow button is sitting on top of an item that I want to remain hovered in grey. More specifically, the item is in a list of items that each will have various buttons appear on top when hovered over.

enter image description here

So with jQuery events:

var selectedItem;
var lastSelectedItem;


$(".item").mouseover(function(){
$(this).addClass("item-hovered")       // css class with hover styles
selectedItem = $(this);
});
$(".item").mouseleave(function(){
$(this).removeClass("item-hovered")
selectedItem = null;
lastSelectedItem = $(this);
});


$(".button").mouseover(function(){
selectedItem = lastSelectedItem;
selectedItem.addClass("item-hovered")
});

"lastSelectedItem" is used to differentiate between moving off item onto whitespace and off item onto button, so selectedItem holds a value only if the mouse is either over an item or its corresponding button.