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

时间:2011-05-30 18:16:49

标签: svg

我对svg路径的boundingbox上的mouseover,mouseout,click事件很感兴趣。例如,鉴于此代码:

<!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>

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

<!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>

我对使用外部库完成此任务不感兴趣。

2 个答案:

答案 0 :(得分:7)

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

Opera支持boundingBox关键字,但目前尚未在其他浏览器AFAIK中支持。为了使它在任何地方都能工作,最常见的解决方案是添加一个不可见的矩形来捕获事件。

答案 1 :(得分:2)

function bbox(e)
        {       
            if (e && e.getBBox && e.getAttributeNS)
            {   
                var box = e.getBBox();
                var transform = e.getAttributeNS(null, 'transform');
                if (box.x && box.y && box.width && box.height && transform)
                {
                    var rect = document.createElementNS(svgns, 'rect');
                    rect.setAttributeNS(null, 'x', box.x);
                    rect.setAttributeNS(null, 'y', box.y);
                    rect.setAttributeNS(null, 'width', box.width);
                    rect.setAttributeNS(null, 'height', box.height);
                    rect.setAttributeNS(null, 'fill', 'rgba(0,0,0,0)');
                    rect.setAttributeNS(null, 'stroke', 'rgba(0,0,0,0)');
                    rect.setAttributeNS(null, 'transform', transform);              
                    e.parentNode.appendChild(rect);
                    return rect;
                }
            }       

            return null;
        };
相关问题