具有d3.js和height属性的响应式SVG

时间:2018-05-05 06:20:49

标签: javascript d3.js svg

我有两个div元素并排。在第一个div(称为#scatterplot)中,会有一个自动渲染的图表。使用d3.js中的以下代码自动设置SVG容器大小:

var vis = d3.select("#scatterplot")
   //container class to make it responsive
   .classed("svg-container", true)
   .append("svg")
   //responsive SVG needs these 2 attributes and no width and height attr
   .attr("preserveAspectRatio", "xMinYMin meet")
   .attr("viewBox", "0 0 700 700")
   //class to make it responsive
   .classed("svg-content-responsive", true)
   .append("g")
   .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

相应的CSS代码如下:

.svg-container {
    display: inline-block;
    position: relative;
    width: 100%;
    padding-bottom: 100%; /* aspect ratio */
    vertical-align: top;
    overflow: hidden;
}
.svg-content-responsive {
    display: inline-block;
    position: absolute;
    top: 10px;
    left: 0;
}

问题:第二个div名为#wordcloud。我需要根据#wordcloud div来调整#scatterplot的高度。有任何建议如何实现这一目标?

1 个答案:

答案 0 :(得分:1)

您可以使用d3.style()方法在内联样式中设置#wordcloud高度。例如:



var height = d3.select('#scatterplot').node().getBoundingClientRect().height;
d3.select('#wordcloud').style('height', height + 'px');

div {
  width: 50%;
  float: left;
}

#scatterplot {
  background: #f00;
}

#wordcloud {
  background: #0f0;
}

<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/3.4.11/d3.min.js"></script>
<div id="scatterplot">
  <p>The text is used<br/>to change height<br/>of red div.</p>
</div>
<div id="wordcloud">
  <p>The heights of red and green divs are same.</p>
</div>
&#13;
&#13;
&#13;