Ric*_*nop 23 javascript jquery
所以我创建一个新的图像元素,一旦我从AJAX调用响应像这样的图像元数据:
var loadedImageContainter = $('<div class="loaded-image-container"></div>');
var image = $('<img src="' + file.url + '" alt="">');
loadedImageContainter.append(image);
$('.loading-image').replaceWith(loadedImageContainter);
var width = image.width();
var height = image.height();
console.log(width);
console.log(height);
Run Code Online (Sandbox Code Playgroud)
但是width()和height()函数返回0,尽管图像大小为30 x 30 px并且它在页面上正确显示.我需要获得它的尺寸才能绝对定位图像.
ahr*_*ren 53
您需要等到图像加载后才能访问宽度和高度数据.
var $img = $('<img>');
$img.on('load', function(){
console.log($(this).width());
});
$img.attr('src', file.url);
Run Code Online (Sandbox Code Playgroud)
或者使用简单的JS:
var img = document.createElement('img');
img.onload = function(){
console.log(this.width);
}
img.src = file.url;
Run Code Online (Sandbox Code Playgroud)
此外,在读取宽度和高度值之前,您无需将图像插入DOM中,因此您可以.loading-image在计算所有正确位置之前保留替换图像.
这是因为检查宽度时未加载图像
尝试以这种方式使用load事件
$('img').on('load',function(){
// check width
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
50977 次 |
| 最近记录: |