如何在D3中为文本div的特定部分着色?
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了如何在D3中为文本div的特定部分着色?相关的知识,希望对你有一定的参考价值。
问题:如何仅为D3中的文本div的特定部分着色?
我知道在html中,这将是<text><span class="red">70,000</span>
受伤的人是白人。但是我如何在D3中做到这一点? B / c追加仅生成子元素。无法在1行中的文本元素中追加2个span元素...
D3代码
var size = [60,50,40,30];
var fontColor = ["iconRed","iconBlue", "iconGreen", "iconOrange"];
var sizeScale = d3.scaleLinear().domain([1, 2, 3,4]).range(size);
var fontColorScale = d3.scaleLinear().domain([1, 2, 3,4]).range(fontColor);
var y_position = 420;
race_frequency_array.forEach(function(element){
graph1.append("text")
.attr("id", "raceLabel")
.attr("x", xPadding)
.attr("y", y_position)
.attr("text-anchor", "start")
.attr("alignment-baseline", "hanging")
.style("font-size", sizeScale(element.RowNum) + "px")
.classed(fontColorScale(element.RowNum), true)
.text("70,000 people injured were white");
y_position += sizeScale(element.RowNum)+10;
});
答案
使用foreignObject
是一种选择,但我不建议这样做。相反,我找到了为你实际编码的时间,并使其非常动态。我正在使用tspan
s,这就是如何在长文本中分隔文本并单独设置样式(这也是Mike推荐的方法)。看看我是如何定义数组的,这也使得改变颜色非常动态。
这是一段代码片段:
var size = [60,50,40,30];
var fontColor = ["iconRed","iconBlue", "iconGreen", "iconOrange"];
var sizeScale = d3.scaleLinear().domain([1, 2, 3,4]).range(size);
var fontColorScale = d3.scaleLinear().domain([1, 2, 3,4]).range(fontColor);
var race_frequency_array = [
[
{text: '70%', color: '#d9534f'},
{text: ' of people killed were '},
{text: 'BLACK', color: '#d9534f'}
],
[
{text: '20%', color: '#5bc0de'},
{text: ' of people killed were '},
{text: 'WHITE', color: '#5bc0de'}
],
[
{text: '7%', color: '#5cb85c'},
{text: ' of people killed were '},
{text: 'LATINO', color: '#5cb85c'}
],
[
{text: '3%', color: '#f0ad4e'},
{text: ' of people killed were '},
{text: 'ASIAN', color: '#f0ad4e'}
]
];
var graph1 = d3.select('svg')
.append('g').attr('class', 'texts');
var xPadding = 10, y_position = 0;
var texts = graph1.selectAll('text').data(race_frequency_array)
.enter().append("text")
.attr("id", "raceLabel");
texts
.attr("x", xPadding)
.attr("y", function(d, i) {
y_position += sizeScale(i)+10;
return y_position;
})
.attr("text-anchor", "start")
.attr("alignment-baseline", "hanging")
.style("font-size", function(d, i) { return sizeScale(i) + "px"});
var tspans = texts.selectAll('tspan')
.data(function(d) { return d; });
tspans.enter()
.append('tspan')
.style('fill', function(d) { return d.color; })
.style('font-weight', '600')
.text(function(d) { return d.text; });
// y_position += sizeScale(element.RowNum)+10;
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg width="1200" height="400"></svg>
以上是关于如何在D3中为文本div的特定部分着色?的主要内容,如果未能解决你的问题,请参考以下文章