繁体   English   中英

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

[英]Set element height equal to width using Vanilla javascript

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

使用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> 

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';
  }

暂无
暂无

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

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