lin*_*ran 32 javascript svg d3.js
我正在使用d3js来查找svg元素的宽度,代码如下所示:
<script>
var body = d3.select("body");
console.log(body);
var svg = body.select("svg");
console.log(svg);
console.log(svg.style("width"));
</script>
<svg class="svg" height="3300" width="2550">
<image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image>
<rect class="word" id="15" x="118" y="259" width="182" height="28"
text="Substitute"></rect>
</svg>
Run Code Online (Sandbox Code Playgroud)
但是它返回了这个错误:
未捕获的TypeError:无法调用null的方法'getPropertyValue'
我认为,svg变量是一个空数组.
如何使用d3js获取svg元素的宽度?
And*_*kyi 31
<svg class="svg" height="3300" width="2550">
<image x="0" y="0" height="3300" width="2550" xlink:href="1.jpg"></image>
<rect class="word" id="15" x="118" y="259" width="182" height="28"
text="Substitute"></rect>
</svg>
<script>
var body = d3.select("body");
console.log(body);
var svg = body.select("svg");
console.log(svg);
console.log(svg.style("width"));
</script>
Run Code Online (Sandbox Code Playgroud)
只需在浏览器加载svg元素后放置脚本,一切都会好的.
gre*_*reg 17
如果你有一个SVG元素w/id = frame ...
frame = d3.select('#frame')
.attr('class', 'frame')
fh = frame.style("height").replace("px", "");
fw = frame.style("width").replace("px", "");
Run Code Online (Sandbox Code Playgroud)
fh和fw现在可用于数学表达式.
你也可以回到jQuery
fw = console.log($("#frame").width());
fh = console.log($("#frame").height());
Run Code Online (Sandbox Code Playgroud)
这些是数字,可用于数学表达式
var svg = d3.select("body")
.append("svg")
.attr("width", "100%")
.attr("height", "100%");
var w = parseInt(svg.style("width"), 10);
var h = parseInt(svg.style("height"), 10);
Run Code Online (Sandbox Code Playgroud)
除非您初始化属性(宽度)的值,否则您最终会得到值“auto”,我会推荐下面的值。
d3element.getBoundingClientRect().width;
Run Code Online (Sandbox Code Playgroud)
或者
var element = d3.select('.ClassName').node();
element.getBoundingClientRect().width;
Run Code Online (Sandbox Code Playgroud)