べにやまぶろぐ

技術寄りの話を書くつもり

D3.js で mouseover/mouseout のイベントがひたすら発火するときは mouseenter/mouseleft を試してみる

バージョン : D3.js 3.0.4

追加検証用のメモエントリーです。こちら適当なサンプルを組んでみた*1のですが

で左側の赤いのは mouseover/mouseout イベント、右側の青いのは mouseenter/mouseleave イベントを捉えるようにしてあるのですが左だと四角形の中を動かしているだけでもひたすら mouseover/mouseout イベントが発火しているのがわかるかと思います。

SVG のエレメント的には

<g transform="translate(50,50)">
    <rect x="0" y="0" width="200" height="200" fill="red" opacity="0.5"></rect>
    <rect x="25" y="25" width="150" height="150" fill="red" opacity="1"></rect>
    <text x="100" y="100" text-anchor="middle" style="font-size: 14pt; fill: #ffffff; stroke: #ffffff;">mouseover &amp; out</text>
</g>

となっており外側の g エレメントに対してイベントハンドラをアタッチしているのですが、そもそもそれがまずいのか。mouseover/mouseout に関しては外側の四角形のエリアを動かしているだけでもイベントが発火し続けるときとしないときがあるのでもうちょっと調べないとという感じです。

参考になるのは Mouseenter - bl.ocks.org で、

Mouseenter and mouseleave events are triggered only when the mouse enters or leaves the parent container; unlike mouseover and mouseout, they are not triggered when the mouse moves between descendant elements.

というように書いてあります。

*1:イベント発火を表示する flash() は Mouseenter - bl.ocks.org を参考にしました