javascript - 尝试在纯 JS 中获取元素的渲染高度时元素为 null

标签 javascript html css

为什么不this代码工作?我正在尝试(不使用 JQuery)获取 html 元素的渲染高度。下面这段代码:

html:

<body id="logo">
</body>

CSS:

body { 
    background-image: url('https://www.gstatic.com/images/branding/googlelogo/2x/googlelogo_color_284x96dp.png');
    background-repeat: no-repeat;
    background-attachment: fixed;
    background-size: 100vw auto;
    background-position: -80px 50%; 
}

JS:

var element = document.getElementById(logo).offsetHeight;
console.log(element);

但是这段代码给出了这个错误:

VM227:51 Uncaught TypeError: Cannot read property 'offsetHeight' of null

我做错了什么?

最佳答案

你的代码应该更像这样:

document.getElementById('logo')

否则你试图将带有 id 的元素放入 var 标识中。

问候

关于javascript - 尝试在纯 JS 中获取元素的渲染高度时元素为 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36500692/

相关文章:

javascript - 为什么 jQuery 不能处理附加内容?

javascript - 如何自动检测特定 Div 的 scrollTop 位置?

html - 浏览器调整大小后出现空白

javascript - js 和 html 中的 onmouseout 行为

asp.net - BootMetro 定义网格布局的宽度

html - 无法将我的 div 放在页面中央

javascript - 在 Postman 中提示用户输入

javascript - 如何用svg连接不同位置的点?

javascript - jquery获取CSS多列中可见列的文本

html - 两侧溢出