【问题标题】:d3 get element or object under current mousepointer?d3 获取当前鼠标指针下的元素或对象?
【发布时间】:2017-06-23 17:11:06
【问题描述】:

如何在 d3 中获取当前位于鼠标下的对象(例如节点、边、路径或其他)?

我想将鼠标移到 svg 的任何部分和 console.log 元素上。

【问题讨论】:

标签: javascript d3.js svg


【解决方案1】:

D3 没有用于此的本地方法。但是,您可以在 mousemove 事件中将 d3.mouse()document.elementFromPoint() 结合使用:

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>

【讨论】:

  • 作品完全接受您的回答并投票感谢您的出色回答
【解决方案2】:

不需要 d3,这可以用 js 和/或 jQuery 完成:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-23
    • 2011-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多