我有一个多线系列图的图例。
我想要做的是点击图例中的圆圈时填充圆圈白色,但是留下轮廓以显示未选中它,然后我将更改主图表中的线条。
我遇到的问题是if语句似乎。
这是图例代码;
(function() {
d3.legend = function(g) {
g.each(function() {
var g= d3.select(this),
items = {},
svg = d3.select(g.property("nearestViewportElement")),
legendPadding = g.attr("data-style-padding") || 5,
lb = g.selectAll(".legend-box").data([true]),
li = g.selectAll(".legend-items").data([true])
lb.enter().append("rect").classed("legend-box",true)
li.enter().append("g").classed("legend-items",true).attr('type','checkbox')
svg.selectAll("[data-legend]").each(function() {
var self = d3.select(this)
items[self.attr("data-legend")] = {
pos : self.attr("data-legend-pos") || this.getBBox().y,
color : self.attr("data-legend-color") != undefined ? self.attr("data-legend-color") : self.style("fill") != 'none' ? self.style("fill") : self.style("stroke")
}
})
items = d3.entries(items).sort(function(a,b) { return a.value.pos-b.value.pos})
li.selectAll("text")
.data(items,function(d) { return d.key})
.call(function(d) { d.enter().append("text")})
.call(function(d) { d.exit().remove()})
.attr("y",function(d,i) { return i+"em"})
.attr("x","1em")
.text(function(d) { ;return d.key})
li.selectAll("circle")
.data(items, function(d) { return d.key})
.call(function(d) { d.enter().append("circle")})
.call(function(d) { d.exit().remove()})
.attr("cy",function(d,i) { return i-0.25+"em"})
.attr("cx",0)
.attr("r","0.4em")
.style("fill",function(d) {(d.value.color);return d.value.color})
.on("click", function(d) {
d3.select(this)
if (this.display != "none") {
this.style("display", "")
} else {
this.style("display", "none")
}
});
// Reposition and resize the box
var lbbox = li[0][0].getBBox()
lb.attr("x",(lbbox.x-legendPadding))
.attr("y",(lbbox.y-legendPadding))
.attr("height",(lbbox.height+2*legendPadding))
.attr("width",(lbbox.width+2*legendPadding))
})
return g
}
})()
我遇到的问题是onclick语句
.on("click", function(d) {
d3.select(this)
if (this.display != "none") {
this.style("display", "")
} else {
this.style("display", "none")
}
});
在此,我试图更改显示,但是当我点击圆圈时我得到了这个错误
"物业'风格'对象#不是函数"
关于如何在声明工作的情况下进行此onclick的任何想法?
答案 0 :(得分:1)
您需要d3.select(this)
再次使用.style()
。但是,您也可以将条件放在样式表达式中:
d3.select(this)
.style("display", this.display != "none" ? "" : "none");
从您的问题来看,您似乎也希望在点击时更新内部状态,例如
d3.select(this)
.style("display", this.display = (this.display == "none" ? "" : "none"));
答案 1 :(得分:0)
如果您尝试更改SVG的显示属性,则无需更改显示样式,即可更改显示属性:
.on("click", function(d) {
this.display = this.display != "none" ? "none" : "";
});
可见性属性也是如此,请参阅此处了解所有SVG属性:MDN
如果您要更改样式,请查看CSS文档:CSS Display