svg路径边界框上的鼠标事件

mor*_*eus 6 svg

我感兴趣的是mouseover,mouseout,在svg路径的boundingbox上点击事件.例如,鉴于此代码:

<!doctype html>
<html>
<head>
</head>
<body>
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<circle id="circle" cx="100" cy="50" r="40" stroke="black"
stroke-width="2" />
</svg>
<script>
    document.ready = (function()
    {   
        var circle = document.getElementById('circle');
        circle.setAttributeNS(null, 'fill', 'rgb(255,255,0)');
        circle.onmouseover = function (e)
        {
            e.target.setAttributeNS(null, 'fill', 'rgb(255,0,0)');
        };
        circle.onmouseout = function (e)
        {
            e.target.setAttributeNS(null, 'fill', 'rgb(255,255,0)');
        };
    })();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

当你将鼠标放入和取出时,圆圈会改变填充颜色,而如果你将鼠标放入和移出边界框,我希望它能改变颜色.我已经在下面尝试了,它不起作用:

<!doctype html>
<html>
<head>
</head>
<body>
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">

<circle id="circle" cx="100" cy="50" r="40" stroke="black"
stroke-width="2" />
</svg>
<script>
    document.ready = (function()
    {   
        var circle = document.getElementById('circle');
        circle.setAttributeNS(null, 'fill', 'rgb(255,255,0)');
        circle.getBBox().onmouseover = function (e)
        {
            circle.setAttributeNS(null, 'fill', 'rgb(255,0,0)');
        };
        circle.getBBox().onmouseout = function (e)
        {
            circle.setAttributeNS(null, 'fill', 'rgb(255,255,0)');
        };
    })();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

我对使用外部库执行此任务不感兴趣.

Eri*_*röm 7

您还可以在路径元素上使用pointer-events="boundingBox"(请参阅SVG Tiny 1.2)来获取在边界框上检测到的鼠标事件,而不是路径本身.

OperaboundingBox支持该关键字,但到目前为止还没有其他浏览器AFAIK.为了使它在任何地方都能工作,最常见的解决方案是添加一个不可见的矩形来捕获事件.

  • [在SVG 2草案中,属性值已更改为"边界框"](http://www.w3.org/TR/SVG2/interact.html#PointerEventsProp),现在Chrome/Chromium支持它 (5认同)