繁体   English   中英

如果使用 JavaScript 的百分比值,如何获得 CSS 的高度和宽度?

[英]How to get CSS height and width if they are in percentage value using JavaScript?

如果使用 JavaScript 的百分比值,如何获得 CSS 的高度和宽度?

假设 CSS 规则:

.field {
  height:50%;
  width:25%;
}

我们尝试了什么:

let a = document.getElementById("field");
console.log(a.style.height)

这给了我空字符串。 有什么方法可以使用 JavaScript 获得高度百分比?

元素 a 的高度占其父元素的百分比可以计算为

getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%'

这可行,但是已经设置了 a 的 styles 及其父级(通过类,通过内联样式设置)。 这与找出高度最初是按百分比还是按其他单位设置的不同。

这是一个简单的例子:

 let a = document.querySelector(".field"); console.log(getComputedStyle(a).height.replace('px','') / getComputedStyle(a.parentElement).height.replace('px','') * 100 + '%');
 .container { height: 50vh; width: 30vw; }.field { height:50%; width:25%; }
 <div class="container"> <div class="field"></div> </div>

Height = a.offsetHeight Width = a.offsetWidth 这给出了以像素为单位的高度和宽度。 不管它是如何在 CSS 中声明的。

在 css 规则中,字段为 dot = class,在 js 中,您正在尝试 getElelmentById。

在 css 规则中将.field 更改为 #field 并尝试...

#field{
   height:50%;
   width:25%;
 }

您可以使用 getComputedStyle

 let elem = document.getElementById('field');
 let ht = window.getComputedStyle(elem, null).getPropertyValue("height");
 console.log(ht)

暂无
暂无

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

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