javascript - D3.js 图表响应行为

标签 javascript jquery d3.js

当窗口宽度发生变化时,我尝试设置监听器以使用 jQuery 更改图表宽度:

// Get width of parent div with jQuery

var widthContainer = $( ".chart" ).parent().width();

//set margins
// margin conventions https://bl.ocks.org/mbostock/3019563

var margin = {top: 0, right: 0, bottom: 30, left: 40};
var width = widthContainer - margin.left - margin.right;
var height = 211 - margin.top - margin.bottom;

// set chart dimensions

var chart = d3.select(".chart")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");


// listener

function changeWidth(){
   widthContainer = $( ".chart" ).parent().width();
   width = widthContainer - margin.left - margin.right;
}

$(window).resize(function(){
  changeWidth();
  console.log(widthContainer);
});

changeWidth() 函数更改 widthContainer 变量,但图表尺寸不会更改。为什么?

这是一个工作代码笔(第 13 到 40 行): http://codepen.io/aitormendez/pen/LbRyWa?editors=0011

提前谢谢

最佳答案

您当前的changeWidth()仅计算新的宽度。您需要将新宽度设置为您想要的元素。 您还需要更新图表 x 比例并重新绘制图表。

快速更新您的codepen(我将changeWidth和resize移动到底部并添加重绘功能)。

var redraw = function(newWidth) {
  // update xscale
  escalax.range([0, newWidth]);
  d3.select('.xaxis').call(xAxis);
  deuda.selectAll("rect")
    .attr("width", function(d) {
      return rr(escalax(d[1]));
    });
  recono.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[2]));
    });
  provee.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1] + d[2]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[3]));
    });
  credito.selectAll("rect")
    .attr("x", function(d) {
      return rr(escalax(d[1] + d[2] + d[3]));
    })
    .attr("width", function(d) {
      return rr(escalax(d[3]));
    });
}

function changeWidth() {
  widthContainer = $(".chart").parent().width();
  width = widthContainer - margin.left - margin.right;

  // update chart width
  d3.select('.chart')
    .attr('width', width);

  // redraw chart
  redraw(width);
}

$(window).resize(function() {
  changeWidth();
  console.log(widthContainer);
});

http://codepen.io/anon/pen/JbboQL?editors=1010

关于javascript - D3.js 图表响应行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40648113/

相关文章:

javascript - 如何使用 Bookshelf.js 正确更新模型?

javascript - 组合对象数组的特定属性

javascript - 区分垂直和水平图像格式 jQuery

jquery - 如何使用 Jquery 在午夜使 Cookie 过期?

d3.js - 在 D3 中使用画笔设置初始缩放

javascript - 在力向图 d3 中拖动整个节点

javascript - 在其他列表的基础上填充列表

javascript - 在 HTML5 Canvas 中绘制任意形状

jquery - 从 HTML5 拖放和 jquery 获取完整文件路径

javascript - 当某些节点被删除时更新 D3 树