javascript 如何使 SVG 文本元素“可点击”?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12905808/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make an SVG text element "click-through-able"?
提问by Cystack
I have a map with SVG text elements to name the locations. I want the locations (shapes) to be clickable, and they are, but because the text elements are on top of them, if someone hovers over a text element and clicks, then nothing happens because the shape was not clicked : the text element was. How can I make it so that if the text element is clicked, the click goes "through" it and to the shape ?
我有一张带有 SVG 文本元素的地图来命名位置。我希望位置(形状)是可点击的,并且它们是可点击的,但是因为文本元素在它们上面,如果有人将鼠标悬停在文本元素上并点击,那么没有任何反应,因为没有点击形状:文本元素是. 我怎样才能做到这样,如果点击文本元素,点击“通过”它并到达形状?
回答by Matt Stone
Mozilla introduced a CSS property for this purpose called pointer-events. It was originally limited to SVG shapes, but is now supported on most DOM elements in modern browsers:
Mozilla 为此引入了一个 CSS 属性,称为pointer-events。它最初仅限于 SVG 形状,但现在现代浏览器中的大多数 DOM 元素都支持它:
span.label { pointer-events: none; }
The answer to this question has some good information on achieving the same result in old IE:
这个问题的答案有一些关于在旧 IE 中实现相同结果的很好的信息:
回答by william malo
add this css to the text:
将此css添加到文本中:
pointer-events: none;
回答by user2009125
If it is possible to group the map shapes with the text inside of a "<g>" element, then you can attach the click to the group rather than the shape. Doing this also gives the added benefit of transforms applied to the group will apply to both the shape and the text. If grouping is not possible, then I agree the previous answer is definitely your best shot. Essentially what is happening is this: most people visualize a click penetrating downward through your z-index, but it doesn't work that way. The click bubbles up through the DOM, so if the text doesn't handle the click, it bubbles up to the next DOM element which is the parent group or container. This continues upward until it reaches the topmost DOM element.
如果可以使用“<g>”元素内的文本对地图形状进行分组,那么您可以将点击附加到组而不是形状。这样做还提供了额外的好处,即应用于组的变换将同时应用于形状和文本。如果无法分组,那么我同意之前的答案绝对是您最好的选择。基本上正在发生的事情是这样的:大多数人想象一个点击向下穿透你的 z-index,但它不是这样工作的。点击在 DOM 中向上冒泡,所以如果文本不处理点击,它会向上冒泡到下一个 DOM 元素,即父组或容器。这将继续向上,直到到达最顶部的 DOM 元素。