如何获取动态创建的图片元素的clientWidth与clientHeight
如何获取动态创建的图片元素的clientWidth与clientHeight
嘿,我懂你这会儿的困惑——刚用jQuery动态创建了图片元素,加到div里后立刻去拿clientWidth和clientHeight,结果全是0,对吧?这事儿我之前也碰过,其实问题出在图片还没加载完成呢!
当你把img元素append到DOM里的时候,浏览器只是把这个元素的结构加上去了,但图片的实际资源还在请求、加载的过程中,这时候元素还没有实际的渲染尺寸,所以clientWidth和clientHeight自然返回0。
解决这个问题的核心思路就是:等图片完全加载完成后,再去获取它的宽高。这里给你两种靠谱的实现方式:
方式一:监听图片的load事件
这是最常用的方法,图片加载完成后会触发load事件,我们在这个事件的回调里去拿宽高就没问题了:
// 假设你已经从文件输入框拿到了第一个文件对象 const firstFile = $('input[type="file"]')[0].files[0]; // 把文件转成可访问的URL const imgUrl = URL.createObjectURL(firstFile); // 创建图片元素 const $img = $('<img>').attr('src', imgUrl); // 监听load事件,加载完成后再处理 $img.on('load', function() { // 现在就能拿到正确的clientWidth和clientHeight了 const imgWidth = this.clientWidth; const imgHeight = this.clientHeight; console.log('图片实际渲染宽高:', imgWidth, imgHeight); // 再把图片添加到目标div里(也可以先添加再监听,不影响结果) $('#image-container').append($(this)); }); // 别忘了加个错误监听,防止图片加载失败导致代码卡住 $img.on('error', function() { console.error('哎呀,这张图片加载失败了'); });
方式二:处理已缓存的图片
如果你的图片是已经被浏览器缓存过的(比如第二次上传同一张图),load事件可能会在你绑定监听之前就触发了,这时候我们可以先检查图片的complete属性:
const firstFile = $('input[type="file"]')[0].files[0]; const imgUrl = URL.createObjectURL(firstFile); const $img = $('<img>').attr('src', imgUrl); // 先判断图片是否已经加载完成 if ($img[0].complete) { // 缓存的图片直接拿宽高 const imgWidth = $img[0].clientWidth; const imgHeight = $img[0].clientHeight; console.log('缓存图片宽高:', imgWidth, imgHeight); $('#image-container').append($img); } else { // 未缓存的图片还是用load事件监听 $img.on('load', function() { const imgWidth = this.clientWidth; const imgHeight = this.clientHeight; console.log('新图片宽高:', imgWidth, imgHeight); $('#image-container').append($(this)); }); }
简单来说,就是别着急,等图片真的“显示”出来了,再去拿它的尺寸——毕竟浏览器得先拿到图片的资源,才能算出它该渲染成多大呀!
内容来源于stack exchange
相关产品推荐
相关产品推荐

