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

html - Zoomed images don't have different sizes according to JavaScript - Stack Overflow

programmeradmin2浏览0评论

Is there any way to get the actual size of a zoomed image via javascript? After adding a css zoom affect to the image and then getting the size via JS it returns the original size.

var img = document.getElementById('img');
var box = document.getElementById('box')

box.innerHTML += "<br />height: " 
    + img.height +
    "px<br />width: "
    + img.width + "px";
#img{zoom:20%}
<div id="box">
  <img id="img" src=".Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>

Is there any way to get the actual size of a zoomed image via javascript? After adding a css zoom affect to the image and then getting the size via JS it returns the original size.

var img = document.getElementById('img');
var box = document.getElementById('box')

box.innerHTML += "<br />height: " 
    + img.height +
    "px<br />width: "
    + img.width + "px";
#img{zoom:20%}
<div id="box">
  <img id="img" src="https://tse2.mm.bing/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>

https://codepen.io/tinkersncody/pen/dyxENwq

Share Improve this question edited Nov 19, 2024 at 0:56 Timur 2,2971 gold badge6 silver badges14 bronze badges asked Nov 18, 2024 at 21:41 MikeMike 6177 silver badges27 bronze badges 3
  • Please, post a minimal reproducible example here, not on an external unreliable (not to criticize codepen, maybe it is very reliable and will last a thousand years. But we have no control on that), probably ephemere, site. Plus, SO already have the equivalent with snippets. – chrslg Commented Nov 19, 2024 at 0:24
  • That's because they don't: the image doesn't change dimensions, only the image element does, so check the element's dimensions using the function mentioned by Timur. – Mike 'Pomax' Kamermans Commented Nov 19, 2024 at 1:23
  • (And on a modern webdev note: don't use + for strings, don't use <br>, and don't set innerHTML unless you really need to set HTML code. Put a span in that div, and set its .textContent using template string syntax. E.g. const span = box.querySelector(`span`); span.textContent =`height: ${...}, width: ${...}`;) – Mike 'Pomax' Kamermans Commented Nov 19, 2024 at 1:25
Add a comment  | 

1 Answer 1

Reset to default 2

You can use the getBoundingClientRect() method:

var img = document.getElementById('img');
var box = document.getElementById('box')

img.onload = () => {
  box.innerHTML += "<br />height: " 
    + img.getBoundingClientRect().height
    + "px<br />width: "
    + img.getBoundingClientRect().width
    + "px";
}
#img{zoom:20%}
<div id="box">
  <img id="img" src="https://tse2.mm.bing/th/id/OIP.Lt_KplHna5Rxc5JdcOAXuQHaHa?rs=1&pid=ImgDetMain" />
</div>

img.onload = () => {...} is added to make sure image is loaded before getting the values.

发布评论

评论列表(0)

  1. 暂无评论