getBoundingClientRect() 给出的是父元素而不是目标元素的尺寸

问题描述 投票:0回答:1

我对网页设计相当陌生,所以提前道歉。我有一个简单的网站网格布局。其中一个单元格内部是一张带有 object-fit: contains 的图像,以使其具有响应能力。

我正在尝试获取图像显示时的实际尺寸。问题是 getBoundingClientRect() 给我的是父 div 的尺寸,而不是图像本身。我想要图像大小的全部原因是为了考虑信箱。

在下面,您可以根据函数轻松地看到宽度>高度,即使我使用了纵向格式示例图像。所以它从父级获取值。

编辑澄清:我现在看到这些是 img 标签的正确值,但不是实际图像的正确值。有什么方法可以得到这些值吗?

function getImageSize() {
  const image = document.querySelector('#sample_image');
  var imgBounds = image.getBoundingClientRect();
  console.log(imgBounds);
}
window.onload = getImageSize;
window.onresize = getImageSize;
* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

.wrapper {
  display: grid;
  border-style: solid;
  border-color: red;
  grid-template-columns: repeat(3, 1fr);
  grid-template-rows: repeat(5, 1fr);
  grid-gap: 10px;
  width: 100vw;
  height: 100vh;
}

.instructions {
  border-style: solid;
  border-color: blue;
  grid-column: 1 / -1;
  grid-row: 1;
}

.elements {
  border-style: solid;
  border-color: yellow;
  grid-column: 1;
  grid-row: 2 / -1;
}

.examples {
  border-style: solid;
  border-color: violet;
  grid-column: 2 / -1;
  grid-row: 2 / -1;
  background-color: #d3d3d3;
  position: relative;
}

.examples img {
  width: 100%;
  height: 100%;
  object-fit: contain;
}
<html>

  <body>
    <div class="wrapper">
      <div class="instructions">text1</div>
      <div class="elements">text2</div>
      <div class="examples">
        <img src="https://upload.wikimedia.org/wikipedia/commons/9/9b/Gustav_chocolate.jpg" id="sample_image" />
      </div>
    </div>

  </body>

</html>

JSFiddle也显示了问题。

javascript css-grid
1个回答
0
投票

要获取图像本身的实际尺寸,您可以在 JavaScript 中使用图像元素的naturalWidth 和naturalHeight 属性。以下是修改函数以检索图像尺寸的方法:

function getImageSize() {
  const image = document.querySelector('#sample_image');
  const imgWidth = image.naturalWidth;
  const imgHeight = image.naturalHeight;
  console.log('Image Width:', imgWidth, 'Image Height:', imgHeight);
}

window.onload = getImageSize;
window.onresize = getImageSize;

这将为您提供图像内容本身的实际宽度和高度,无论它在父容器中如何显示。

© www.soinside.com 2019 - 2024. All rights reserved.