是否可以在元素的一部分上触发:hover?

我正在尝试在CSS中创建自定义工具提示实现,效果相当不错,但遇到了问题。当前,即使我没有将鼠标悬停在原始元素本身上,也仍然将鼠标悬停在工具提示上。

Of course I've tried something like ::before:hover {display:none;}, but that doesn't work because pseudo-elements don't get pseudo-classes applied to them.

My next thought was to simply make the tooltip not "take up" any space. Using negative margin-bottom allows other stuff to take up space in an element as if the element is not there. However, the :hover pseudo-class apparently still applies then.

A minimal example of what I'm trying to accomplish is this: I'd like this div to only trigger :hover in the top half, without having to overlay some other element on top of the div. The span elements indicate the computed top and bottom of the div, as can be verified using developer tools.

div {
  width: 100px;
  height: 100px;
  background: red;
  margin-bottom: -50px;
  position: relative;
   z-index: 1;
}
div:hover {
  background: blue;
}
span {
  text-align: right;
  float: right;
  width: 100%;
  border-top: 1px solid black;
}
<span>top of the div</span>
<div></div>
<span>bottom of the div</span>

For a slightly more sophisticated example, I'd like to have the tooltip of the following demo not persist any hovering state. Note that moving the tooltip-text higher above the element is not a working solution, because moving the cursor upwards faster than a snail's pace will cause some pixels to be skipped, which means the tooltip 'catches' the cursor and persists the :hover on the element.

[data-tooltip] {
  position: relative;
  cursor: default;
}
[data-tooltip]:hover::before {
  content: attr(data-tooltip);
  position: absolute;
  top: -2px;
  transform: translateY(-100%);
  background: white;
  border: 1px solid black;
}
<p>Spacer text</p>
<div data-tooltip="Example tooltip">Hover over me for a tooltip text</div>

如您所见,如果将光标移至div上方,则将显示工具提示,如果将光标缓慢向上移,则工具提示将消失。但是,如果将光标稍微向上移动一点,它将跳过1像素的间隙,并使光标悬停在div上。

Now I'm looking for some styles to apply to [data-tooltip]::before so that the cursor's hover events are not triggered on it (or at least, not at the location you see the tooltip; if I can hide it somewhere at [-1000, -1000] that's fine as well)

So basically, my question is, is it possible to apply css to an element so that :hover does not apply to (part of) an element? I'd love to hear ideas or suggestions.

评论
  • zomnis
    zomnis 回复

    If you add the rule z-index: 0 to the [data-tooltip] it give the expected result:

    [data-tooltip] {
      position: relative;
      cursor: default;
    }
    
    [data-tooltip]:hover::before {
      content: attr(data-tooltip);
      position: absolute;
      top: -2px;
      transform: translateY(-100%);
      background: white;
      border: 1px solid black;
      z-index: 0;
    }
    <p>Spacer text</p>
    <div data-tooltip="Example tooltip">Hover over me for a tooltip text</div>