2011-05-30 51 views
5

我对mouseover,mouseout,点击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> 

我对使用外部库不感兴趣。

回答

6

您也可以使用pointer-events="boundingBox"(见SVG Tiny 1.2)路径元素上获得的外接矩形框,而不是路径本身上检测到的鼠标事件。

boundingBox关键字在Opera中被支持,但到目前为止还没有在其他浏览器中被AFAIK支持。为了使它在任何地方都能正常工作,最常见的解决方案是添加一个不可见的矩形来捕获事件。

+4

[在SVG 2草案中,属性值已更改为'bounding-box'](http://www.w3.org/TR/SVG2/interact.html#PointerEventsProp),现在Chrome /铬 – LeartS 2014-08-04 17:00:59

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