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

6

我对svg路径的边界框上的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个回答

9
您还可以在路径元素上使用pointer-events="boundingBox"(请参见SVG Tiny 1.2),以便检测到鼠标事件发生在边界框上而不是路径本身。
目前,boundingBox关键字在Opera中得到支持,但据我所知,在其他浏览器中并未得到支持。为了使其在所有浏览器中都能正常工作,最常见的解决方案是添加一个不可见的矩形来捕获事件。

6
在SVG 2草案中,属性值已更改为“bounding-box”,并且现在已被Chrome/Chromium支持。 - LeartS

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;
        };

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接