我对 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/