在d3图表层次结构中添加子类



我试图在工具提示下方和工具栏上方添加一个小三角形。

因此我遵循这个文档-http://bl.ocks.org/caged/6476579

对于工具提示,我写了下面的代码-
var tip = d3Tip()
.attr("class", "d3-tip")
.style("line-height", 1)
.style("font-weight", "bold")
.style("padding", "12px")
.style("background", "rgba(0, 0, 0, 0.8)")
.style("color", "#fff")
.style("border-radius", "2px")
.attr("class", ":after")
.style("box-sizing", "border-box")
.style("display", "inline")
.style("font-size", "10px")
.style("width", "100%")
.style("color", "rgba(0, 0, 0, 0.8)")
.style("content", "\25BC")
.style("position", "absolute")
.style("text-align", "center")
.offset([-10, 0])
.html(function (_data, indexedData) {
var htmlToolTip = "";
keys.map((key, index) => {
htmlToolTip +=
"<strong>" +
key +
" : </strong> <span style='color:red'>" +
indexedData.data[key + "Value"] +
"</span> <br>";
});
return htmlToolTip;
});

在这里,我试图添加下面的类属性-

/*为工具提示创建一个小三角形扩展器*/

.d3-tip:after {
box-sizing: border-box;
display: inline;
font-size: 10px;
width: 100%;
line-height: 1;
color: rgba(0, 0, 0, 0.8);
content: "25BC";
position: absolute;
text-align: center;
}

但是没有在工具提示下面添加三角形。

您首先需要知道什么是':after'
在CSS中,::after或(:after)创建一个伪元素,它是所选元素的最后一个子元素。它通常用于向具有content属性的元素添加修饰内容。默认为内联。

您在代码中所做的是,您只对d3-tip进行了样式化,并且在该tip中没有插入:after。你假设d3-tip和:after是相同的元素,但它们是分开的。要插入它,您必须执行remove:after element的css(您将该css添加到您的提示父元素中),并稍后将其插入实际的:after伪元素。在d3中,您可以使用d3.insert为类添加一个子元素。

你的代码应该看起来像下面

var tip = d3Tip()
.attr("class", "d3-tip")
.style("line-height", 1)
.style("font-weight", "bold")
.style("padding", "12px")
.style("background", "rgba(0, 0, 0, 0.8)")
.style("color", "#fff")
.style("border-radius", "2px")
.offset([-10, 0])
.html(function (_data, indexedData) {
var htmlToolTip = "";
keys.map((key, index) => {
htmlToolTip +=
"<strong>" +
key +
" : </strong> <span style='color:red'>" +
indexedData.data[key + "Value"] +
"</span> <br>";
});
return htmlToolTip;
});
d3.select('.d3-tip').insert(":after")
.style("box-sizing", "border-box")
.style("display", "inline")
.style("font-size", "10px")
.style("width", "100%")
.style("color", "rgba(0, 0, 0, 0.8)")
.style("content", "\25BC")
.style("position", "absolute")
.style("text-align", "center");

d3.select (.d3-tip) .insert(":after")这条语句将使它成为d3-tip的子元素,您可以对它进行样式设置。我相信这会解决你的问题。

最新更新