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

标签 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, '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>

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

最佳答案

您也可以使用 pointer-events="boundingBox" (请参阅 SVG Tiny 1.2 )在路径元素上获取在边界框而不是路径本身上检测到的鼠标事件。
boundingBox Opera 中支持关键字,但到目前为止还没有在其他浏览器中 AFAIK。为了让它在任何地方都能工作,最常见的解决方案是添加一个不可见的矩形来捕获事件。

关于svg - svg 路径边界框上的鼠标事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6179514/

相关文章:

css - 如何确保 flexbox 容器中的图像按比例缩放?

javascript - 使用 d3.js 和 TypeScript 绘制饼图时出现编译错误

javascript - D3.js:缩放 svg 时错过刻度线

javascript - 使用 svg.js 反转蒙版

javascript - d3fc.js d3fc JavaScript 中线系列的设置类

html - 有没有办法在嵌入网页时隐藏 SVG 文件/xml 的内容?

javascript - 用于移动任何 SVG 元素的通用 JS 函数

object - 为什么 HTML anchor 标记不包装可缩放的 SVG <object>?

android - 如果动态加载,SVG 不会在 android 和 safari 上播放动画

HTML CSS : Make Google Icon into Button without Rectangle around it