<!DOCTYPE html>
<html>
<head>
<script data-require="[email protected]" data-semver="4.0.0" src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/chance/1.0.8/chance.min.js"></script>
</head>
<body>
<script>
var w = 300,
h = 300;
var data = [
{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
},{
x: Math.random() * (w - 100),
y: Math.random() * h,
t: chance.word()
}
]
var svg = d3.select('body')
.append('svg')
.attr('width', w)
.attr('height', h);
const labels = svg.selectAll('text').data(data);
labels.enter()
.append('text')
.attr('class', (d) => `label-${d.t}`)
.attr('x', (d) => d.x)
.attr('y', (d) =>d.y)
.text((d) => d.t)
.each(function(d){
var bbox = this.getBBox();
svg.append('rect')
.attr('x', bbox.x)
.attr('y', bbox.y)
.attr('width', bbox.width)
.attr('height', bbox.height)
.style('fill', 'none')
.style('stroke', 'steelblue');
});
</script>
</body>
</html>
,我不得不去'。每次((d,I,J)= > {const bbox = j [i] .getBBox(); ...}'来完成这个工作,但是你的代码工作。谢谢 – Benjamin
@Benjamin,这是因为你正在使用胖箭头符号而不是常规函数''='' ,通过设计,压制通过将'this'放入函数中。 – Mark