最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - how can i get element height in javascript - Stack Overflow

programmeradmin2浏览0评论

I have tried this and it just brings an empty space in console of my browser. How can can i get the height of my element.

var background = document.getElementById('bgimage');
console.log(background.style.height);
.background {
  width: 100%;
  height: 500vh;
}
<div class="section s1">
  <div class="background" id="bgimage">
    .......
  </div>
</div>

I have tried this and it just brings an empty space in console of my browser. How can can i get the height of my element.

var background = document.getElementById('bgimage');
console.log(background.style.height);
.background {
  width: 100%;
  height: 500vh;
}
<div class="section s1">
  <div class="background" id="bgimage">
    .......
  </div>
</div>

Share Improve this question edited May 18, 2020 at 6:21 asked Nov 30, 2019 at 10:01 user12424171user12424171 2
  • 2 Does this answer your question? How do you get the rendered height of an element? – BadPiggie Commented Nov 30, 2019 at 10:04
  • element.style.height refers to inline style only. – connexo Commented Nov 30, 2019 at 15:12
Add a ment  | 

4 Answers 4

Reset to default 5

Use offsetHeight:

var background = document.getElementById('bgimage');
var h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
console.log(background.offsetHeight*100/h);
.background {
width: 100%;
height: 500vh;
}
<div class="section s1">
<div class="background" id="bgimage">
   .......
</div>
</div>

Note: element.offsetHeight will return height of element in pixels (px).

An element's clientHeight is a measurement that includes the element CSS height and the element vertical padding and, if rendered, subtracting the height of the horizontal scrollbar.

try background.clientHeight

Just fix your javascript code

var background = document.getElementById('bgimage');
var bgimage = getComputedStyle(background);
console.log(bgimage.getPropertyValue('height'));

This is my function to get offsetHeight. Basically it get clientHeight and then add with paddingTop and paddingBottom (if any) to get offsetHeight value. By definition offsetHeight = clientHeight+paddingTop+paddingBottom.

I'm using clientHeight because sometimes the offsetHeight always get 0 value, but clientHeight will always have value (as far as I know).

function getOffsetHeight(el) {
  var hh = 0;
  if (el) {
    hh = el.clientHeight;
    if (el.style.paddingTop != "") {
      hh += parseInt(el.style.paddingTop);
    }
    if (el.style.paddingBottom != "") {
      hh += parseInt(el.style.paddingBottom);
    }
  }
  return hh;
}
发布评论

评论列表(0)

  1. 暂无评论