使用原生的Javascript将元素高度设置为宽度

4

我有一个包含10个元素的节点列表,通过以下方式获取:

let elements = document.getElementById('all-photos-root').querySelectorAll('.photo-root');

这给了我一个包含10个元素的NodeList。每个元素的初始宽度以百分比设置为25%。我想将每个元素的高度设置为相等的像素宽度,以便它始终呈现为正方形。

我尝试以下方法,但总是得到未定义的宽度。

for (var i = 0; i < elements.length; i++) {
    console.log('elements', elements[i], elements[i].style.width);
    elements[i].style.height = elements[i].style.width;
}

1
尝试使用 getComputedStyle() - 31piy
2个回答

5

使用Element#style将只能获取已设置为 inline 的属性(在style 属性中的属性,css 中的属性不会被包括在内)。

如果您想获取当前活动的属性,应该使用getComputedStyle

您还可以使用offsetWidthclientWidthscrollWidth 获取块的宽度(以像素为单位的数字格式)。

var foo = document.getElementById("foo");
var bar = document.getElementById("bar");
var fooBar = document.getElementById("foo-bar");

console.log("Foo:");
console.log(foo.style.width); // 30px
console.log(getComputedStyle(foo).width); // 30px
console.log(foo.offsetWidth);

console.log("Bar:");
console.log(bar.style.width); // hasn't been defined using style attribue
console.log(getComputedStyle(bar).width); // 40px as defined in #bar css block
console.log(bar.offsetWidth);

console.log("FooBar:");
console.log(fooBar.style.width); // hasn't been defined using style attribute
console.log(getComputedStyle(fooBar).width); // will actually give the absolute width in `px` instead of the `50%` used in css block
console.log(fooBar.offsetWidth);
#bar {
  width: 40px;
}

#foo-bar {
  width: 50%;
}
<div id="foo" style="width: 30px;"></div>
<div id="bar"></div>
<div id="foo-bar"></div>


4
for (var i = 0; i < elements.length; i++) {

    // width and height in pixels, including padding and border
    // Corresponds to jQuery outerWidth()
    let width = elements[i].offsetWidth;

    // width and height in pixels, including padding, but without border
    // Corresponds to jQuery innerWidth()
    width = elements[i].clientWidth;

    // Need to add the px at the end
    elements[i].style.height = width + 'px';
  }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接