如何在SVG中检测鼠标悬停

时间:2016-02-19 11:55:27

标签: javascript html5 svg

我有这样简单的SVG图表:

<svg id="ss" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" class="chart" width="1000" height="300" >
    <g>
        <rect fill="#aaaaaa" stroke-width="0" stroke="none" height="1" width="1000" y="200" x="0" /> </g>
    <g class="bar">
        <rect height="81.858" width="30" y="118.142" x="10" />
    </g>
    <g class="bar">
        <rect height="111.6012" width="30" y="88.3988" x="55" />
    </g>
    <g class="bar">
        <rect height="66.98639999999999" width="30" y="133.0136" x="100" />
    </g>
</svg>

如何使用纯javascript检测rect元素上的鼠标?并知道哪个矩形元素正在结束?

1 个答案:

答案 0 :(得分:2)

直接分配事件有什么问题?

var rects = document.querySelectorAll( 'rect' );
for( var rect of rects ) {
    rect.addEventListener( 'mouseover', cb );
}

function cb(){
  // the "this" object is your reference to the rect hovered over
  console.log( this );
}