我怎样才能用d3把一个圆圈放在前面

我怎样才能用d3把一个圆圈放在前面

本文介绍了我怎样才能用d3把一个圆圈放在前面?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

首先,我使用 d3.js 在数组中显示不同大小的圆圈.在鼠标悬停时,我希望被鼠标悬停的圆圈变大,我可以做到,但我不知道如何将它带到前面.目前,一旦它被渲染,它就会隐藏在多个其他圆圈后面.我该如何解决这个问题?

First of all, I am using d3.js to display different sized circles in arrays. On mouse over, I want the circle being moused over to become bigger, which I can do, but I have no idea how to bring it to the front. Currently, once it's rendered, it's hidden behind multiple other circles. How can I fix this?

这是一个代码示例:

   .on("mouseover", function() {
    d3.select(this).attr("r", function(d) { return 100; })
  })

我尝试使用排序和排序方法,但它们不起作用.我很确定我没有做对.有什么想法吗?

I tried using the sort and order methods, but they didn't work. I'm pretty sure i didn't do it correctly. Any thoughts?

推荐答案

TL;DR

对于最新版本的 D3,您可以使用 selection.raise(),如 tmpearce其答案中.请向下滚动并点赞!

With latest versions of D3, you can use selection.raise() as explained by tmpearce in its answer. Please scroll down and upvote!

原答案

您必须更改对象的顺序并使鼠标悬停的圆圈成为添加的最后一个元素.正如您在此处看到的:https://gist.github.com/3922684 并按照 nautat,您必须在主脚本之前定义以下内容:

You will have to change the order of object and make the circle you mouseover being the last element added. As you can see here: https://gist.github.com/3922684 and as suggested by nautat, you have to define the following before your main script:

d3.selection.prototype.moveToFront = function() {
  return this.each(function(){
    this.parentNode.appendChild(this);
  });
};

然后你只需要在鼠标悬停时调用你的对象上的 moveToFront 函数(比如 circles):

Then you will just have to call the moveToFront function on your object (say circles) on mouseover:

circles.on("mouseover",function(){
  var sel = d3.select(this);
  sel.moveToFront();
});

正如 Henrik Nordberg 所建议的,有必要绑定数据通过使用 .data() 的第二个参数到 DOM.这对于不失去对元素的约束是必要的.请阅读 Henrick 的回答(并点赞!)了解更多信息.作为一般建议,在将数据绑定到 DOM 时始终使用 .data() 的第二个参数,以利用 d3 的全部性能功能.

As suggested by Henrik Nordberg it is necessary to bind the data to the DOM by using the second argument of the .data(). This is necessary to not lose binding on elements. Please read Henrick's answer (and upvote it!) for more info. As a general advice, always use the second argument of .data() when binding data to the DOM in order to leverage the full performance capabilities of d3.

正如 Clemens Tolboom 所提到的,反向函数是:

As mentioned by Clemens Tolboom, the reverse function would be:

d3.selection.prototype.moveToBack = function() {
    return this.each(function() {
        var firstChild = this.parentNode.firstChild;
        if (firstChild) {
            this.parentNode.insertBefore(this, firstChild);
        }
    });
};

这篇关于我怎样才能用d3把一个圆圈放在前面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 05:04