Vanilla JS和D3中获取元素宽高像素值的方法

所谓Vanilla JS,其实就是原生的JavaScript,不依赖于任何库。好吧,这只是个黑话。

在布局处理中,常常需要获取元素的宽高像素值,通常这些元素的宽高是自适应的,或是使用百分比指定,在这种情况下,需要获取其像素宽高,通常在D3应用中,这种情况尤其常见。

假设有元素<div id="container">,需要获取其宽高像素值。

Vanilla JS:

1
2
3
let c = document.getElementById("container"); //获取Element对象
let width = c.getBoundingClientRect().width; //获取像素宽度
let height = c.getBoundingClientRect().height; //获取像素高度

而在D3中,可以使用select达到同样效果:

1
2
3
let svg = d3.select("#container");
let width = svg.node().getBoundingClientRect().width;
let height = svg.node().getBoundingClientRect().height;