使用D3时出现cannot read property 'offsetHeight' of null错误求助
解决
cannot read property 'offsetHeight' of null错误 嘿,这个问题其实很好搞定!你看代码里的这两行:
var width = document.getElementById("#container").offsetWidth, height = document.getElementById("#container").offsetHeight,
这里犯了个小疏忽——document.getElementById()的参数不需要加#前缀!它直接接收元素的纯ID字符串,你加了#之后,浏览器找不到匹配ID的元素,就返回了null,自然就会抛出读取offsetHeight属性失败的错误啦。
修复后的代码
把多余的#去掉就行:
d3.select("#container") .style("height", "100%") .style("width", "100%") .style("position", "relative") .style("bottom", 0); var width = document.getElementById("container").offsetWidth, height = document.getElementById("container").offsetHeight, radius = (Math.min(width, height) / 1.5);
额外小建议
既然你已经用D3选中了容器元素,其实可以直接复用这个选中结果,不用再重复调用原生的getElementById,代码会更简洁统一:
var container = d3.select("#container") .style("height", "100%") .style("width", "100%") .style("position", "relative") .style("bottom", 0) .node(); // 用.node()获取对应的原生DOM元素 var width = container.offsetWidth, height = container.offsetHeight, radius = (Math.min(width, height) / 1.5);
这样既避免了重复查询DOM,也能保证你操作的是同一个元素,一举两得~
内容的提问来源于stack exchange,提问作者Robin van Hoorn
相关产品推荐
相关产品推荐

