使用Vanilla JavaScript将元素高度设置为等于宽度

时间:2019-08-09 07:05:37

标签: javascript html css dom domdocument

我在下面使用的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;
}

2 个答案:

答案 0 :(得分:3)

使用Element#style仅会获得内联设置的属性(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>

答案 1 :(得分:1)

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';
  }
相关问题