【问题标题】:get image size inside <img> tag with object-fit [duplicate]使用对象匹配获取 <img> 标记内的图像大小 [重复]
【发布时间】:2021-10-25 11:51:57
【问题描述】:

如何获取已在浏览器上呈现的图像的大小,在带有object-fit: contain 属性的&lt;img /&gt; 标记内?

如您所见,img 标签适合 100% 的容器,但里面的图像不适合。我需要图像的大小,而不是标签

naturalWidth clientWidthwidth 没有返回想要的值

【问题讨论】:

标签: javascript html


【解决方案1】:

你可以使用offsetWidth获取任意元素的width

function func() {
  var imgTag = document.getElementById("imgTag")
  var demo = document.getElementById("demo")
  
  demo.innerHTML = imgTag.offsetWidth

}
<img src="https://pixy.org/src/477/4774988.jpg" width="200" height="200" id="imgTag" />
<button onclick="func()">Get width</button>
<div id="demo"></div>

【讨论】:

  • 我需要标签内的图像大小,而不是标签
  • 到目前为止,只有标签大小的方法。此外,当您使用object-fit 时,它只会更改 image 的位置。就像cover 中的图像将跨越整个区域一样,contain 中的图像将根据它保持其纵横比和跨度。您可以通过将 background-color 赋予大小与 object-fit 属性不匹配的 img 标记来看到这一点。此外,在图像不跨越 contain 的情况下,大小保持不变,您不能写入或使用该区域。因此,要使用它,您必须仅减小 img 标记的大小
【解决方案2】:

You can usewindow.getComputedStyle()

let para = document.querySelector('p');

let imgWithNoStyle = document.getElementById('noStyle');
let imgWithStyle = document.getElementById('withStyle');

let imgWithNoStyles = window.getComputedStyle(imgWithNoStyle);
let imgWithStyles = window.getComputedStyle(imgWithStyle);

para.textContent = `
  My computed img with no style is: 
  ${imgWithNoStyles.objectFit} 
  ${imgWithNoStyles.width} 
  ${imgWithNoStyles.height}
  and my computed img with style is: 
  ${imgWithStyles.objectFit} 
  ${imgWithStyles.width} 
  ${imgWithStyles.height}
`;
.with-style {
  width: 200px;
  height: 300px;
  border: 5px solid black;
  object-fit: fill;
}
<p>Hello</p>

<img src="https://www.w3schools.com/tags/img_girl.jpg" id="noStyle">

<img src="https://www.w3schools.com/tags/img_girl.jpg" id="withStyle" class="with-style">

【讨论】:

  • jsfiddle.net/9xpgt5o6 如果将object-fit 更改为contain,并将高度更改为150pximg.height 将返回标签的高度,而不是内部的图像
  • 那么图像大小保持不变,它(object-fit)只改变图像的位置。就像cover 中的图像将跨越整个区域一样,contain 中的图像将根据它保持其纵横比和跨度
【解决方案3】:
document.querySelector("img").naturalWidth;

【讨论】:

  • "naturalWidth ...返回所需的值"
  • 虽然此代码可能会回答问题,但提供有关它如何和/或为什么解决问题的额外上下文将提高​​答案的长期价值。您可以在帮助中心找到更多关于如何写好答案的信息:stackoverflow.com/help/how-to-answer。祝你好运?
猜你喜欢
  • 2017-10-05
  • 1970-01-01
  • 2018-06-01
  • 2013-02-27
  • 2021-12-23
  • 2011-09-04
  • 2014-04-30
  • 1970-01-01
  • 2011-11-09
相关资源
最近更新 更多