【发布时间】:2019-02-06 06:09:42
【问题描述】:
当我尝试使用 D3 调整事件的大小时,它显示我在图表中附加的元素“g”在调整大小期间重复打印。如何使用this 关键字?或类似的东西?
This is the code on js fiddle.
问题:如何使用 d3 中的this 关键字解决?
function redraw(){
let chartContainer = document.getElementById("bar_Chart");
let containerWidth = chartContainer.clientWidth;
let containerHeight = chartContainer.clientHeight;
let inputData = [
{name: "JAN", value: 10},
{name: "FEB", value: 8},
{name: "MAR", value: 15},
{name: "APR", value: 16},
{name: "MAY", value: 23},
{name: "JUN", value: 30},
{name: "JUL", value: 12},
{name: "AUG", value: 41},
{name: "SEP", value: 52},
{name: "OCT", value: 23},
{name: "NOV", value: 32},
{name: "DEC", value: 42}
];
let margin = {top: 20, right: 30, bottom: 30, left: 40};
let width = containerWidth - margin.left - margin.right;
let height = containerHeight - margin.top - margin.bottom;
let x = d3.scaleBand()
.rangeRound([0, width])
.padding(0.1);
let y = d3.scaleLinear()
.range([height, 0]);
let tooltip = d3.select("body").append("div").attr("class", "toolTip");
let chart = d3.select(".chart-svg")
.attr("width", width + margin.left + margin.right)
.attr("height", height + margin.top + margin.bottom)
.append("g")
.attr("transform", "translate(" + margin.left + "," + margin.top + ")");
x.domain(inputData.map(function(d) { return d.name; }));
y.domain([0, d3.max(inputData, function (d) { return d.value; })]);
let xAxis = d3.axisBottom(x);
let yAxis = d3.axisLeft(y);
chart.append("g")
.attr("class", "x axis")
.attr("transform", "translate(0," + height + ")")
.call(xAxis)
chart.append("g")
.attr("class", "y axis")
.call(yAxis)
chart.selectAll(".bar")
.data(inputData)
.enter().append("rect")
.attr("class", "bar")
.attr("x", function(d) { return x(d.name); })
.attr("y", function(d) { return y(d.value); })
.attr("height", function(d) { return height - y(d.value); })
.attr("width", x.bandwidth())
.on("mouseover", function (d) {
tooltip.transition()
.duration(200)
.style("opacity", 0.85)
.style("left", d3.event.pageX - 50 + "px")
.style("top", d3.event.pageY - 70 + "px");
tooltip
.style("display", "inline-block")
.html((d.name) + "£" + (d.value));
d3.select(this).transition()
.duration(300)
.style("fill", "red");
})
.on("mouseout", function () {
tooltip.transition()
.duration(200)
.style("opacity", 0);
tooltip
.style("display", "none");
d3.select(this).transition()
.duration(300)
.style("fill", "steelblue")
.style("transition", "scale(1.8)");
});
}
redraw();
window.addEventListener("resize", redraw);
【问题讨论】:
标签: javascript jquery d3.js