在本文的代码中,当图片加载完成时,会调用 onload 指定的函数。在该函数中,获取了图片的宽、高度。
值得一提的是,设置了图片的 display 为 none,即图片不显示。这方便了我们在获取图片的原始宽、高后对图片尺寸进行调整,之后再显示图片。
<img onload="get_wh(this)" style="display: none;" src="https://andi.cn/images/andi/1.png" /> <script> function get_wh(el) { console.log(el.width, el.height) } </script>