2017-02-06 3 views
1

d3で現在マウスの下にあるオブジェクト(ノード、エッジ、パスなど)を取得するにはどうすればよいですか?d3現在のマウスポインタの下にある要素またはオブジェクトを取得しますか?

私はsvgと要素のconsole.logの任意の部分にマウスを渡したいと思います。

+0

可能な複製(http://stackoverflow.com/questions/1259585/ get-element-at-specified-position-javascript) – altocumulus

答えて

2

D3は、このためのネイティブメソッドを持っていません。しかし、あなたはmousemoveイベントにdocument.elementFromPoint()d3.mouse()を組み合わせることができます

var svg = d3.select("svg"); 
 
svg.on("mousemove", function() { 
 
    var mouse = d3.mouse(this); 
 
    var elem = document.elementFromPoint(mouse[0], mouse[1]); 
 
    console.log(elem.tagName) 
 
})
<script src="https://d3js.org/d3.v4.min.js"></script> 
 
<svg height="150" width="500"> 
 
    <rect x="50" y="20" width="150" height="100" style="fill:blue;stroke:pink;stroke-width:5;fill-opacity:0.1;stroke-opacity:0.9"/> 
 
    <ellipse cx="240" cy="50" rx="220" ry="30" style="fill:yellow"/> 
 
    <ellipse cx="220" cy="50" rx="190" ry="20" style="fill:white"/> 
 
    <circle cx="350" cy="50" r="40" stroke="black" stroke-width="3" fill="red" /> 
 
    <line x1="0" y1="0" x2="200" y2="200" style="stroke:rgb(255,0,0);stroke-width:4"/> 
 
</svg>

[指定された位置にゲット要素 - のJavaScript]の
+0

あなたは完璧に受け入れられています。 – commonSenseCode

0

は、このためにd3はJSおよび/またはjQueryを使って行うことができる必要はありませんでした:

$("body").click(function(event) { 
    console.log("clicked: " + event.target.nodeName, event.target); 
}); 
関連する問題