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

问题描述

| 我对鼠标悬停,鼠标悬停,svg路径的边界框上的单击事件感兴趣。例如,给出以下代码:
<!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,0)\');
        };
        circle.onmouseout = function (e)
        {
            e.target.setAttributeNS(null,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,0)\');
        circle.getBBox().onmouseover = function (e)
        {
            circle.setAttributeNS(null,0)\');
        };
        circle.getBBox().onmouseout = function (e)
        {
            circle.setAttributeNS(null,0)\');
        };
    })();
</script>
</body>
</html>
我对使用外部库执行此任务不感兴趣。     

解决方法

        您还可以在path元素上使用
pointer-events=\"boundingBox\"
(请参见SVG Tiny 1.2),以在边界框而不是路径本身上检测到鼠标事件。 Opera中支持
boundingBox
关键字,但到目前为止,其他浏览器AFAIK均不支持。为了使它在任何地方都可以使用,最常见的解决方案是添加一个不可见的矩形来捕获事件。     ,        
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)\');
                    rect.setAttributeNS(null,\'stroke\',\'transform\',transform);              
                    e.parentNode.appendChild(rect);
                    return rect;
                }
            }       

            return null;
        };
    

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...