Get Computed Height - Javascript - Not jQuery

别说谁变了你拦得住时间么 提交于 2020-03-18 21:47:08

问题


I have two divs side by side set to height auto. I want them to have equal height, so i combined them as members of an array.

I recurse through the array and set the not-tallest ones to the height of the tallest. Problem is everything i have tried to get the COMPUTED height has resulted in the incorrect value.

I have tried the following:

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

h =  el.clientHeight || el.offsetHeight || el.scrollHeight;

Both of these are yielding 640 px'ish while the computed is 751.8 in my particular showing.

Is there possbily a constant I can use to get the correct height. Like maybe the number im getting would be on a standard size screen (like 960 pixels high or such) then multiple that by the window size?


回答1:


I have had a lot of good use of this little function I came up with

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.

This will return the height of any given elements given to the function (by it's ID). So now we'r 1/3 of the way.

Then use the Math.max() function to get the height of the largest element.

var maxH = Math.max(getH("ID1"),getH("ID2")); 

This is 2/3 of the way, YAY - Now set the elements height to be the same.

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 "".

DONE!! - Now put it all together

I would imagine something like this

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

This WILL set both ID's to the same height and the height WILL be equal to the highest. That is what you want, isn't it?

--EDIT--

I would throw away the array if I were you. Just have the 2 DIV's each with a unique ID and make them equally tall based upon that.

  • Molle



回答2:


If you have the DOM document, you can try the below code:

let divElement = document.getElementById('divId');
let height = document.defaultView.getComputedStyle(divElement).height;

'height' will have the exact height of the element with 'divId' once it is computed.



来源:https://stackoverflow.com/questions/20153026/get-computed-height-javascript-not-jquery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!