简体   繁体   中英

how to get the actual dimensions of the element displayed in viewport

在此处输入图像描述

As you can see in the image the dimension is 388 x 274.83

but, when console the things console.log(e.offsetWidth,e.offsetHeight,e.getBoundingClientRect()) the values I got which is different.

The html looks like this with applied transform

<div id="element" style="width: 360px; transform-origin: 0px 0px 0px; transform: matrix(1.07778, 0, 0, 1.07778, 0, 0);">
<div id="content" class="sidebar__content p-2" style="overflow: hidden; position: relative;">
  <div class="bg-E4E4E4 segmentaion-viewer p-2 " id="elementContainer" style="filter: brightness(100%) contrast(1) saturate(1);" tabindex="0">
    <div id="element" style="width: 360px; transform-origin: 0px 0px 0px; transform: matrix(1.07778, 0, 0, 1.07778, 0, 0);">
      <div class="imageNameStyle">cado1.jpg</div>
      <div class="segment-annotator-outer-container" id="imgOuterContainer" style="width: 360px; height: 255px;">
        <div id="segmentContainer" class="segment-annotator-inner-container" style="width: 360px; height: 255px;">
          <svg id="svgHook" style="pointer-events: none;"></svg>
          <canvas width="360" height="255" class="segment-annotator-layer image-layer" id="canvasLayer"></canvas>
        </div>
      </div>
    </div>
  </div>
</div>
onload: function () { // onload of image
 let h = document.getElementById("element")
 console.log(h.scrollWidth,h.scrollHeight,h.getBoundingClientRect())
}

Anyone knows how to get the actual dimensions of the element displayed in viewport?

The.getBoundingClientRect() method should do the magic... try to pay attention to the transformation matrix css attribute... because probably you call the console.log() before the style is being applied.

In alternative to.getBoundingCLientRect() you could use something like:

    var element = document.getElementById(/* your element id */);   //or use a different selector
    var computedStyle = getComputedStyle(element);

    
    var effective_height =  element.clientHeight + parseFloat(computedStyle.paddingTop) + parseFloat(computedStyle.paddingBottom) + parseFloat(computedStyle.marginTop) + parseFloat(computedStyle.marginBottom);
    var effective_width =  element.clientWidth + parseFloat(computedStyle.paddingRight) + parseFloat(computedStyle.paddingLeft) + parseFloat(computedStyle.marginRight) + parseFloat(computedStyle.marginLeft);

    //an alternative

    var effective_height =  element.scrollHeight;
    var effective_width =  element.scrollWidth;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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