获得计算高度 - Javascript - 不是jQuery

Mag*_*sso 5 javascript height

我有两个div并排设置为高度auto.我希望它们具有相同的高度,所以我将它们组合成阵列的成员.

我通过阵列递归并将最高的那些设置为最高的高度.问题是我试图让COMPUTED高度导致错误值的一切.

我尝试过以下方法:

(els[x].currentStyle) ? h=els[x].currentStyle.height : h=window.getComputedStyle(els[x],null).height;

h =  el.clientHeight || el.offsetHeight || el.scrollHeight;
Run Code Online (Sandbox Code Playgroud)

这两个都产生640 px'ish,而在我的特定显示中计算的是751.8.

有可能我可以用来获得正确的高度.就像我可能获得的数字将是标准尺寸的屏幕(如960像素高或类似)然后多个窗口大小?

Nam*_*val 8

如果你有 DOM 文档,你可以尝试下面的代码:

let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;
Run Code Online (Sandbox Code Playgroud)

计算后,“height”将具有具有“divId”的元素的准确高度。


Mol*_*lle 6

我已经很好地利用了我提出的这个小功能

function getH(id)
{
    return document.getElementById(id).offsetHeight;
}
// I have a styles.js file where this function feels right at home. Access this function from anywhere.
Run Code Online (Sandbox Code Playgroud)

这将返回给予函数的任何给定元素的高度(通过它的ID).所以现在我们是1/3.

然后使用Math.max()函数获取最大元素的高度.

var maxH = Math.max(getH("ID1"),getH("ID2")); 
Run Code Online (Sandbox Code Playgroud)

这是2/3,YAY - 现在将元素高度设置为相同.

var x = document.getElementById("ID1");
var y = document.getElementById("ID2");

x.style.height = maxH +"px";
y.style.height = maxH +"px";  //Remember the +"px" has to be added as a string, thats the reason for the "".
Run Code Online (Sandbox Code Playgroud)

DONE! - 现在把它们放在一起

我会想象这样的事情

function setElementHeight()
{
    var maxH = Math.max(getH("ID1"),getH("ID2"));
    var x = document.getElementById("ID1");
    var y = doc...("ID2");
    x.style.height = maxH +"px";
    y.style.height = maxH +"px";
}
// Don't forget to include the first function in you'r .js file
Run Code Online (Sandbox Code Playgroud)

这将把两个ID设置为相同的高度,高度将等于最高.这就是你想要的,不是吗?

- 编辑 -

如果我是你,我会扔掉阵列.只需拥有2个DIV,每个DIV都有一个独特的ID,并在此基础上使它们同样高大.

  • 莫勒