DOM元素仅在添加到父级时具有维度,因为维度由呈现引擎确定.要解决此问题,<div>请将一个容器绝对放在屏幕外,首先将图像添加到其中,获取尺寸,然后在其最终目的地添加图像.
就像是 :
var _offscreen = $('<div></div>')
.css({position:'absolute',left:'-999999px',width:'400px',height:'600px'})
.appendTo($('body'));
var img = $('<img>/img>')
.attr('src',"http://l1.yimg.com/a/i/ww/news/2011/03/25/zo.jpg")
.load(function() {
var $this = $(this);
$this.appendTo(_offscreen);
setTimeout(function() {
var width = $this.width();
var height = $this.height();
alert($this.attr('src') + ' = ' + width + "x" + height);
}, 0);
});
Run Code Online (Sandbox Code Playgroud)
**编辑**
我刚刚更新了上面的代码.事实证明,你需要让渲染引擎绘制图像(当然!)然后获得维度.所以编辑工作.
这可以放在一个方便的功能,如:
$('imageElement').loadImage("path/to/image", function() {
alert("Image " + $(this).attr('src') + " loaded: " + $(this).width() + "x" + $(this).height());
});
Run Code Online (Sandbox Code Playgroud)
**更新**
我想你可能希望看到上面的代码放入一个JQuery插件 ...只是为了好玩:)它只是工作,没有完成验证(即它不会检查你是否传递其他元素<img>),如果选择器返回多个元素,插件会将相同的图像加载到每个选定的元素中.你实际上可以让插件参数url成为一个数组(可选)并在每个选定的元素中加载数组的每个图像等等.只是一个想法.
| 归档时间: |
|
| 查看次数: |
2862 次 |
| 最近记录: |