D3js数据可视化V7版本文字提示框信息无法显示问题的解决办法

这学期新学的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());

实验结果如下:

问题就解决啦!(因为刚接触,自己找了好久的问题,都没发现)

 

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值