为什么 div DOM 对象没有高度和宽度属性

Bla*_*ard 1 html javascript css

我是初学者编码器。可能很简单,但我试图找到答案并没有成功。我的问题是为什么对象的属性widthheight属性都div返回,undefined而它们显然都是 100px?

在本主题中解释了如何获取.offsetWidth属性。但据我所知,它与.width.

window.onload = function() {

  var test = document.getElementById("test");
  test.addEventListener("click", select);


  function select(e) {
    var elementID = e.target.id;
    var element = document.getElementById(elementID);
    var width = element.width;
    console.log(element);
    console.log(width);
  }

}
Run Code Online (Sandbox Code Playgroud)
div#test {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: black;
}
Run Code Online (Sandbox Code Playgroud)
<div id="test"></div>
Run Code Online (Sandbox Code Playgroud)

我的答案

谢谢大家的回答。他们推动我找到自己的简单解决方案,我希望这对我这样的初学者有所帮助。答案是:divDOM 对象没有.width.height属性,即使您在 CSS 中分配它们并且它们运行良好。为此,它分别具有.style.width.style.height。但即使您通过 CSS 分配它们,它们也不会出现, element.style除非您有目的地使用 Java Script。因此,要通过 JS获取元素的widthor heightdiv首先要从 CSS 中删除这些属性。您将不再需要它们。然后width通过element.style.width命令分配,然后您可以随时使用element.style.width.

CSS

div {
    position: absolute;
    background-color: black;
}
Run Code Online (Sandbox Code Playgroud)

JavaScript

window.onload = function() {

    var test = document.getElementById("test");
    test.addEventListener("click", select);
    test.style.width = "100px";
    test.style.height = "100px";


    function select(e) {                                  
        var elementID = e.target.id;
        var element = document.getElementById(elementID);
        var width = element.style.width;
        console.log(element);
        console.log(width);
    }

}
Run Code Online (Sandbox Code Playgroud)

Sae*_*aee 5

使用offsetWidthoffsetHeight

var test = document.getElementById("test");
test.addEventListener("click", select);


function select(e) {
  var elementID = e.target.id;
  var element = document.getElementById(elementID);
  var offsetWidth = element.offsetWidth;

  var positionInfo = element.getBoundingClientRect();
  var height = positionInfo.height;
  var width = positionInfo.width;

  console.log('element', element);
  console.log('offsetWidth', offsetWidth);
  console.log('width', width);
  console.log('height', height);
}
Run Code Online (Sandbox Code Playgroud)
div#test {
  position: absolute;
  height: 100px;
  width: 100px;
  background-color: black;
}
Run Code Online (Sandbox Code Playgroud)
<!doctype html>
<html lang="en">

<head>
  <title>test</title>
  <meta charset="utf-8">
</head>

<body>

  <div id="test"></div>

</body>

</html>
Run Code Online (Sandbox Code Playgroud)