mouse events on bounding box of svg path
I am interested in mouseover, mouseout, click events on boundingbox of a svg path. E.g., given this code:
<!doctype html>
<html>
<head>
</head>
<body>
<svg width="100%" height="100%" version="1.1"
xmlns="http://www.w3.org/2000/svg">
<circle id="circle" c开发者_运维百科x="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>
the circle changes fill color when you mouse in and out of it, whereas I would like it to change color if you mouse in and out of its bounding box. I already tried below, and it doesn't work:
<!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>
I am not interested in using an external library for this task.
You could also use pointer-events="boundingBox"
(see SVG Tiny 1.2) on the path element to get the mouse events detected on the boundingbox instead of on the path itself.
The boundingBox
keyword is supported in Opera, but so far not in the other browsers AFAIK. To make it work everywhere the most common solution is to add an invisible rectangle to capture the events.
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;
};
精彩评论