I'm drawing a scatterplot with d3.js. With the help of this question :
Get the size of the screen, current web page and browser window

我用的是这个答案:

var w = window,
    d = document,
    e = d.documentElement,
    g = d.getElementsByTagName('body')[0],
    x = w.innerWidth || e.clientWidth || g.clientWidth,
    y = w.innerHeight|| e.clientHeight|| g.clientHeight;

因此,我能够将我的绘图与用户窗口相匹配,如下所示:

var svg = d3.select("body").append("svg")
        .attr("width", x)
        .attr("height", y)
        .append("g");

现在,当用户调整窗口大小时,我希望有一些东西能够调整绘图的大小.

PS:我的代码中没有使用jQuery.

推荐答案

寻找"响应性SVG"使SVG响应性非常简单,您不必再担心大小.

我是这样做的:

d3.select("div#chartId")
   .append("div")
   // 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 600 400")
   // Class to make it responsive.
   .classed("svg-content-responsive", true)
   // Fill with a rectangle for visualization.
   .append("rect")
   .classed("rect", true)
   .attr("width", 600)
   .attr("height", 400);
.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;
}

svg .rect {
  fill: gold;
  stroke: steelblue;
  stroke-width: 5px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

<div id="chartId"></div>

Note: SVG图像中的所有内容都将随窗口宽度zoom .这包括笔划宽度和字体大小(甚至是那些用CSS设置的).如果不希望这样,下面还有更多涉及的替代解决方案.

更多信息/教程:

http://thenewcode.com/744/Make-SVG-Responsive

http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

Javascript相关问答推荐

JavaScript .Click()函数不起作用

在JavaScript中打开和关闭弹出窗口

在JavaScript中,如何将请求的回调函数的结果合并到运行的代码中?

用相器进行向内碰撞检测

如何在JavaScript中在文本内容中添加新行

有什么(最佳)方法可以从模块中获取脚本模块的多姆元素吗?

如何才能拥有在jQuery终端中执行命令的链接?

未捕获错误:在注销后重定向到/login页面时找不到匹配的路由

InDesign—创建一个独立的窗口,在文档中进行更正时保持打开状态

将2D数组转换为图形

点击按钮一次有文本出现和褪色,而不是点击两次?(html,CSS,JavaScript)

如何在Obsidian dataview中创建进度条

我的服务工作器没有连接到我的Chrome扩展中的内容脚本.我该怎么解决这个问题?

如何解决useState错误—setSelect Image不是函数''

React.Development.js和未捕获的ReferenceError:未定义useState

禁用.js文件扩展名并从目录导入隐式根index.js时,找不到NodeJS导入模块

MarkLogic-earch.suggest不返回任何值

更新Redux存储中的对象数组

如何使用[ModelJSON,ArrayBuffer]调用tf.loadGraphModelSync

如何在加载页面时使锚定标记成为焦点