You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:56:50