gpt4 book ai didi

javascript - 在 d3.js 中显示和隐藏附加元素

转载 作者:太空宇宙 更新时间:2023-11-04 16:26:09 26 4
gpt4 key购买 nike

我有一个简单的脚本(也在 JSFiddle 上),它根据给定的数据绘制散点图。当我查看散点图上的数据点时,脚本应在图表下方显示红色圆圈;反之亦然,当事件“mouseout”被调用时,圆圈应该消失。

现在,当调用“mouseover”事件时,会显示红色圆圈,但该圆圈会附加到其他圆圈上。我想知道在这种情况下如何正确实现显示/隐藏功能。

代码粘贴在下面。

var data = [[4,3], [3,3], [1,4], [2,3]];

var margin = {top: 20, right: 15, bottom: 60, left: 60},
width = 500 - margin.left - margin.right,
height = 250 - margin.top - margin.bottom;

var x = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[0]; })])
.range([ 0, width ]);

var y = d3.scale.linear()
.domain([0, d3.max(data, function(d) { return d[1]; })])
.range([ height, 0 ]);

var chart = d3.select('body')
.append('svg:svg')
.attr('width', width + margin.right + margin.left)
.attr('height', height + margin.top + margin.bottom)
.attr('class', 'chart')

var main = chart.append('g')
.attr('transform', 'translate(' + margin.left + ',' + margin.top + ')')
.attr('width', width)
.attr('height', height)
.attr('class', 'main')

// Draw the x axis
var xAxis = d3.svg.axis()
.scale(x)
.orient('bottom');

main.append('g')
.attr('transform', 'translate(0,' + height + ')')
.attr('class', 'main axis date')
.call(xAxis);

// draw the y axis
var yAxis = d3.svg.axis()
.scale(y)
.orient('left');

main.append('g')
.attr('transform', 'translate(0,0)')
.attr('class', 'main axis date')
.call(yAxis);

var g = main.append("svg:g");

g.selectAll("scatter-dots")
.data(data)
.enter().append("svg:circle")
.attr("cx", function (d,i) { return x(d[0]); } )
.attr("cy", function (d) { return y(d[1]); } )
.attr("r", 5);

// FUNCTION TO DISPLAY CIRCLE BELO CHART
g.on('mouseover', function(){
div.style("display", "block")
div.append("svg")
.attr("width", 50)
.attr("height", 50)
.append("circle")
.attr("cx", 25)
.attr("cy", 25)
.attr("r", 25)
.style("fill", "red");
});

g.on('mouseout', function(){
div.style("display", "none")
});

var div = d3.select("body")
.append("div")
.attr("class", "tooltip")
.style("display", "none");

最佳答案

每次将鼠标悬停在圆圈上时,都会附加一个新的 SVG。

一个简单而懒惰的解决方案是删除“mouseout”上的 SVG:

g.on('mouseout', function(){
div.select("svg").remove();
});

这是你的 fiddle :https://jsfiddle.net/39pmwzzh/

关于javascript - 在 d3.js 中显示和隐藏附加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40199528/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com