d3js:Svg元素在更改窗口大小时未调整大小

问题描述 投票:1回答:3

我有一个svg元素,我试图让它响应。我正在使用的代码如下所示,但这不起作用。我不明白这个问题。

 var svg = d3.select('.chart')
            .append('svg')
            .attr('class', 'chart')
            .attr("width", width + margin + margin)
            .attr("height", height + margin + margin + 10   )
            .attr("viewBox", "0 0 680 490")
            .attr("preserveAspectRatio", "xMinYMin meet")
            .append("g")
            .attr("transform", "translate(" + margin + "," + margin + 
 ")");
javascript d3.js responsive
3个回答
1
投票

你在那里设置宽度和高度。根据经验,我知道设置宽度和高度的SVG很难调整大小。我只使用视图框并使用CSS进行大小调整。


1
投票

该代码只运行一次,并将其大小设置为初始窗口高度和宽度值。如果您希望在更改窗口大小时调整大小,则需要在window.onresize事件上调整大小。

window.onresize = function() {
    // code to change svg element's width/height here
}

0
投票

我找到了解决方案。以下为我工作。不管怎么说,还是要谢谢你 :)

var svg = d3.select('.chart')
            .classed("svg-container", true)
            .append('svg')
            .attr('class', 'chart')
            .attr("viewBox", "0 0 680 490")
            .attr("preserveAspectRatio", "xMinYMin meet")
            .classed("svg-content-responsive", true)
            .append("g")
            .attr("transform", "translate(" + margin + "," + margin + ")");

.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;
}
© www.soinside.com 2019 - 2024. All rights reserved.