2017-02-06 50 views
1

如何獲取當前在d3中鼠標下的對象(例如節點,邊緣,路徑或其他)?d3獲取當前鼠標指針下的元素或對象?

我想將鼠標移過svg的任何部分和console.log元素。

+0

[在指定位置獲取元素 - 的JavaScript]的可能的複製(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>

+0

作品完全接受你的回答,並且upvote謝謝你的出色答案 – commonSenseCode

0

也沒必要D3這個可以用js和/或jQuery的完成:

$("body").click(function(event) { 
    console.log("clicked: " + event.target.nodeName, event.target); 
}); 
相關問題