SVG - 多边形悬停不正确

2022-01-22 00:00:00 polygon hover svg mouse-cursor css

正如您在下面的 gif 中看到的,当我将鼠标光标从底部多边形移动到上部多边形时,:hover 状态无法正常工作:

polygon {笔画宽度:5;中风:红色;填写:无;}多边形:悬停{填充:红色;}

<svg viewBox="0 0 999 799"><多边形点="445,161 345,174 500,10"/><多边形点="445,161 345,174 500,270"/></svg>

在 Chrome 和 Firefox 中测试 - 结果是一样的.

鼠标光标进入边框后,如何实现SVG多边形转:hover状态?

解决方案

没有fill来捕捉指针事件所以失败了.

一个简单的透明填充可以纠正它.

polygon {笔画宽度:1;中风:红色;填充:透明;}多边形:悬停{填充:红色;}

<svg viewBox="0 0 999 799"><多边形点="445,161 345,174 500,10"/><多边形点="445,161 345,174 500,270"/></svg>

正如罗伯特·朗森所说

pointer-events: visible 是首选和高性能解决方案.

polygon {笔画宽度:1;中风:红色;填写:无;指针事件:可见;}多边形:悬停{填充:红色;}

<svg viewBox="0 0 999 799"><多边形点="445,161 345,174 500,10"/><多边形点="445,161 345,174 500,270"/></svg>

As you can see on gif below, :hover state does not work properly when I move the mouse cursor from bottom polygon to upper polygon:

polygon {
  stroke-width: 5;
  stroke: red;
  fill: none;
}

polygon:hover {
  fill: red;
}

<svg viewBox="0 0 999 799">
  <polygon points="445,161 345,174 500,10" />
  <polygon points="445,161 345,174 500,270" />
</svg>

[jsfiddle]

Tested in Chrome and Firefox - the result is the same.

How can I achieve SVG polygon turn :hover state on right after mouse cursor enters its borders?

解决方案

There is no fill to catch the pointer event so it fails.

A simple transparent fill corrects it.

polygon {
  stroke-width: 1;
  stroke: red;
  fill: transparent;
}
polygon:hover {
  fill: red;
}

<svg viewBox="0 0 999 799">
  <polygon points="445,161 345,174 500,10" />

  <polygon points="445,161 345,174 500,270" />
</svg>

As mentioned by Robert Longson

pointer-events: visible is the preferred and performant solution.

polygon {
  stroke-width: 1;
  stroke: red;
  fill: none;
  pointer-events: visible;
}
polygon:hover {
  fill: red;
}

<svg viewBox="0 0 999 799">
  <polygon points="445,161 345,174 500,10" />

  <polygon points="445,161 345,174 500,270" />
</svg>

相关文章