如何使用d3将一个圆圈带到前面? [英] How can I bring a circle to the front with d3?
问题描述
首先,我使用d3.js在数组中显示不同大小的圆。在鼠标结束时,我想要把鼠标移动到更大的圆圈,我可以做,但我不知道如何把它带到前面。目前,一旦它被呈现,它被隐藏在多个其他圈子。
.on(mouseover,function(){
d3.select(this).attr(r,function(d){return 100;})
})
我尝试使用排序和排序方法,但他们没有工作。我确定我没有做到正确。任何想法?
解决方案你将不得不改变对象的顺序,您可以在这里看到: https://gist.github.com/3922684 ,并按照 nautat ,您必须在主脚本之前定义以下内容:
d3.selection.prototype.moveToFront = function(){
return this.each(function(){
this.parentNode.appendChild(this);
});
};
然后你只需要调用 moveToFront
圈子上的对象(例如圈子
.on(mouseover,function(){
var sel = d3.select(this);
sel.moveToFront();
});
编辑:Henrik Nordberg 有必要使用 .data()的第二个参数将数据绑定到DOM
。这是必要的,不会失去对元素的绑定。请阅读Henrick的答案(和upvote它!)了解更多信息。作为一般建议,在将数据绑定到DOM时,始终使用 .data()
的第二个参数,以便充分利用d3的全部性能。
编辑:
如 Clemens Tolboom ,相反的功能是:
d3.selection.prototype.moveToBack = function(){
return this.each(function(){
var firstChild = this.parentNode.firstChild;
if(firstChild){
this.parentNode.insertBefore(this,firstChild);
}
});
};
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?
Here's a code sample:
.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?
解决方案 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);
});
};
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();
});
Edit: 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.
Edit:
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将一个圆圈带到前面?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!