简体   繁体   English

如何使SVG文本元素“点击通过”?

[英]How to make an SVG text element “click-through-able”?

I have a map with SVG text elements to name the locations. 我有一个带有SVG文本元素的地图来命名位置。 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 ? 我怎样才能这样做,如果单击文本元素,点击会“通过”它和形状?

Mozilla introduced a CSS property for this purpose called pointer-events . 为此,Mozilla引入了一个名为pointer-events的CSS属性。 It was originally limited to SVG shapes, but is now supported on most DOM elements in modern browsers: 它最初仅限于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中实现相同结果的好信息:

css 'pointer-events' property alternative for IE IE的“指针 - 事件”属性替代方案

将此css添加到文本中:

pointer-events: none;

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. 如果可以使用“<g>”元素内的文本对地图形状进行分组,则可以将单击附加到组而不是形状。 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. 基本上发生的事情是这样的:大多数人想象出一个点击向下穿过你的z-index,但它不会那样工作。 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. 点击通过DOM向上冒泡,因此如果文本没有处理点击,它会冒泡到下一个DOM元素,即父组或容器。 This continues upward until it reaches the topmost DOM element. 这继续向上,直到它到达最顶端的DOM元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM