这学期新学的D3js数据可视化,因为之前一直用的V3版本,做力导向图鼠标交互的文字框提示时,是像下面这样写的。
//提示框定义
let tooltip = d3.select('body')
.append('div')
.style('position', 'absolute')
.style('z-index', '25')
.style('color', 'black')
.style('visibility', 'hidden')
.style('font-size', '20px')
.style("background-color","white")
.style("opacity",1.0)
.style("stroke-width",2)
.style("border-radius", "10px");
var circles=svg.selectAll("forceCircle")
.data(nodes)
.enter()
.append("circle")
.attr("class","forceCircle")
.attr("r",30)
.style("stroke","black")
.style("stroke-width","1px")
.attr("fill","#41a686")
.on("mouseover",function(d,i){
d3.select(this)
.attr("fill", "red");
return tooltip.html(d.intro)
.style('visibility', 'visible')
;
})
.on('mousemove', function (d, i) {
return tooltip.html(d.intro)
.style('top', (event.pageY-10)+'px')
.style('left',(event.pageX+10)+'px');
})
.on('mouseout', function (d, i) {
d3.select(this)
.attr("fill","#41a686");
return tooltip.style('visibility', 'hidden')
})
.call(force.drag);
当时运行的结果图是
但是将同样的代码段移植到V7版本时,数据没法输入到前端,为了找到是哪儿出现的问题,我在鼠标交互过程中加入向控制台输出信息,发现输出的是undifined。
要解决这个问题,需要在未进入鼠标交互这一过程之前就先定义属性,再进行调用。
以下是我的修改。
//tooltip与之前相同
var node=svg.selectAll(".node")
.data(nodes)
.enter()
.append("circle")
.attr("class","node")
.attr("r",30)
.style("stroke","black")
.style("stroke-width","1.0px")
.attr("fill","#2c9e7a")
.attr("info",(d)=>d.intro)//新增属性
.on("mouseenter",function(d,i){
const node=d3.select(this);
node.attr("fill", "red");
var t=node.attr("info");//新增属性的信息
tooltip.html(t)
.style('visibility', 'visible')
;
})
.on('mousemove', function (d, i) {
const node=d3.select(this);
var t=node.attr("info");
tooltip.html(t)
.style('top', (event.pageY-10)+'px')
.style('left',(event.pageX+10)+'px');
})
.on('mouseout', function (d, i) {
d3.select(this)
.attr("fill","#2c9e7a");
return tooltip.style('visibility', 'hidden')
})
.call(drag());
实验结果如下:
问题就解决啦!(因为刚接触,自己找了好久的问题,都没发现)