简体   繁体   English

获取动态创建的元素(Javascript,DOM)的CSS宽度

[英]Getting CSS width of dynamically created element (Javascript, DOM)

I'm experimenting with adding divs to the DOM programmatically. 我正在尝试以编程方式将divs添加到DOM。 I want to arrange them in a circle within a "master" div , 我想将它们围成一个“ master” div内的圆圈,

<body>
<div id="master">


</div>

<script src="js/main.js"></script>
</body>

thusly: 因此:

window.addEventListener('load',init);

let master;

function init() {
    master = document.getElementById('master');

    const count = 8;
    const radius = 50;
    for (let i=0; i<count;i++){
        const diva = document.createElement('div');
        diva.id = i;
        master.appendChild(diva);
        let {x,y} = returnCoords(100,100,degreesToRad((360/count) * i),radius);
        diva.style.left = x + "px";
        diva.style.top = y + "px";
        console.log(diva.style.width); // empty!
    }

}

function degreesToRad(degrees) {
   return degrees * (Math.PI / 180);

}

function radToDegrees(rad) {
    return radians * (180 / Math.PI);

}

function returnCoords(originX = 0, originY = 0,radians,radius) {
    let x = originX + (Math.cos(radians) * radius);
    let y = originY + (Math.sin(radians) * radius);
    return ({x,y});
}

These div s are styled by SCSS: 这些div由SCSS设置样式:

#master {
  background:pink;
  height:300px;
  width:300px;
  position: relative;
  div {
    background: white;
    height:20px;
    width:20px;
    border:blueviolet solid 1px;
    position:absolute;
  }
}

And this all works fine. 而且一切正常。 However I can't get the width of the div , even after it's added into the DOM. 但是,即使将div添加到DOM后,我也无法获得它的width The line console.log(diva.style.width); console.log(diva.style.width); produces nothing. 什么都不产生。 Thus I can't move the divs based on their width. 因此,我无法根据其宽度移动divs What am I missing? 我想念什么?

The .style property reads the inline styles of an element, not the ones assigned by CSS. .style属性读取元素的内联样式,而不是CSS分配的样式。 Confusing, for sure. 确实令人困惑。 Read more about it here: https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style 在此处了解更多信息: https : //developer.mozilla.org/en-US/docs/Web/API/HTMLElement/style

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM