鼠标事件在重叠SVG行时不起作用

时间:2014-04-09 16:43:29

标签: html5 svg

我有一个这样的页面,这里有两个圆圈,一个是黄色,另一个是红色,当同时放置时,鼠标事件不触发意味着潜在的圆形鼠标事件被隐藏

<!DOCTYPE html>
<html>
<body>

<h1>My first SVG</h1>

<svg width="100" height="100" style="position:fixed;top:50;left:40;z-index:2;">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" onmouseout="evt.target.setAttribute('opacity','1');" onmouseover="evt.target.setAttribute('opacity','0.5');" onclick="alert('yellow clicked')"/>
   Sorry, your browser does not support inline SVG.
</svg> 

<svg width="100" height="100" style="position:fixed;top:50;left:40;z-index:1;">
   <circle cx="50" cy="50" r="20" stroke="green" stroke-width="4" fill="brown" onmouseout="evt.target.setAttribute('opacity','1');" onmouseover="evt.target.setAttribute('opacity','0.5');" onclick="alert('red clicked')"/>
   Sorry, your browser does not support inline SVG.
</svg> 

</body>
</html>

2 个答案:

答案 0 :(得分:0)

svg元素具有属性pointer-events,用于控制是否触发与该元素相关的事件。例如如果您在顶部圆圈上设置pointer-events="none",它会变得透明,因此事件可能发生在底部圆圈

<svg id="mySVG" width="400" height="400">
<circle onclick=alert() id=bottomCircle cx=200 cy=200 r=150 fill=red />
<circle pointer-events="none" id=topCircle cx=200 cy=200 r=130 fill=blue />
</svg>

答案 1 :(得分:0)

现在有效了

<!DOCTYPE html>
<html>
<body>

<h1>My first SVG</h1>

<svg>
<svg width="100" height="100" style="position:fixed;top:50;left:40;z-index:2;">
   <circle cx="50" cy="50" r="40" stroke="green" stroke-width="4" fill="yellow" onmouseout="evt.target.setAttribute('opacity','1');" onmouseover="evt.target.setAttribute('opacity','0.5');" onclick="alert('yellow clicked')"/>
   Sorry, your browser does not support inline SVG.
</svg> 

<svg width="100" height="100" style="position:fixed;top:50;left:40;z-index:1;">
   <circle cx="50" cy="50" r="20" stroke="green" stroke-width="4" fill="brown" onmouseout="evt.target.setAttribute('opacity','1');" onmouseover="evt.target.setAttribute('opacity','0.5');" onclick="alert('red clicked')"/>
   Sorry, your browser does not support inline SVG.
</svg> 
</svg>
</body>
</html>