![](/img/trans.png)
[英]How to set the screen height and width by %(percentage) in javascript
[英]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.