【问题标题】:How to set the exact size of an inline SVG element?如何设置内联 SVG 元素的确切大小?
【发布时间】:2015-07-18 16:49:13
【问题描述】:

我正在使用 d3.js 创建可视化:

http://bl.ocks.org/EE2dev/raw/cd904f10097b9921f1cc/

在该代码中,我创建了一个 SVG 元素并使用此行设置大小:

var chart = d3.select("body")
  .append("div").attr("class", "chart")
  .append("svg")
  .attr("width", outerWidth) // outerWidth = 960
  .attr("height", outerHeight) // outerHeight = 500
  .append("g")
  .attr("class", "margin")
  .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

在 Chrome 中测试代码,一切正常,SVG 的大小为 (960, 500)。但是,当我在 Firefox 中打开此站点时,SVG 元素的大小会有所不同,这似乎取决于实际的浏览器窗口大小,例如(634, 856) 在下面的例子中。

如何解决此问题以将 SVG 设置为 Firefox 所需的固定大小?

我尝试了几件事,包括包装一个 div 和/或遵循我在其他地方找到的想法

但是我没有找到一种方法可以为我解决这个问题:(

任何帮助将不胜感激!

【问题讨论】:

    标签: javascript html firefox svg d3.js


    【解决方案1】:

    outerWidthouterHeight 是浏览器窗口属性。奇怪的问题是这些属性可以在 Chrome 中被覆盖,但在 Firefox 中却不能(FF API)。所以当你设置

    outerWidth = 960;
    

    然后在 Chrome 中将 outerWidth 更改为 960。在 Firefox 的情况下,它是当前窗口宽度,并且不能由客户端脚本更改。 所以重命名 outerWidthouterHeight 它应该可以工作。

    svgWidth = 960;
    svgHeight = 500;
    
    ...
    
    .append("svg")
    .attr("width", svgWidth)
    .attr("height", svgHeight)
    

    【讨论】:

    • 不幸的是,重命名变量甚至直接使用值 (960, 500) 都不会改变 firefox 中的行为。
    • 我错了,你是对的!变量 outerWidth 和 outerHeight 在 Firefox 中被覆盖。当我进行您建议的更改时,我没有注意到,因为我还使用了名称:innerWidth 和 innerHeight。同样的事情也适用。非常感谢!!
    猜你喜欢
    • 1970-01-01
    • 2017-09-07
    • 2015-12-20
    • 2016-01-23
    • 2021-09-04
    • 1970-01-01
    • 2019-10-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多