【发布时间】:2011-10-31 04:14:42
【问题描述】:
我想在将图像附加到浏览器之前输出图像的宽度和高度。 当然,宽度为 0,高度为 0,因为图像尚未附加到 DOM。
我已将我的代码上传到http://jsfiddle.net/BF5En/4/
如何在将图像附加到 DOM 之前获取正确的值??
谢谢,提前!
【问题讨论】:
标签: jquery image height width append
我想在将图像附加到浏览器之前输出图像的宽度和高度。 当然,宽度为 0,高度为 0,因为图像尚未附加到 DOM。
我已将我的代码上传到http://jsfiddle.net/BF5En/4/
如何在将图像附加到 DOM 之前获取正确的值??
谢谢,提前!
【问题讨论】:
标签: jquery image height width append
您的问题似乎很有趣。这是我谦虚的回答:
$(document).ready(function() {
$(".Photos a").click(function () {
var href_attribute = $(this).attr('href');
var new_item = $('<img src="' + href_attribute + '" />')
.hide()
.load(function () {
alert('Img was loaded! Width: ' + this.width + ' and height: ' + this.height);
})
.fadeIn(2000)
.appendTo('.AppendingDiv');
return false;
});
});
现场示例:http://jsfiddle.net/hobobne/BF5En/10/
你看,你必须确保图像是预加载的,为此我们使用.load()。否则你会得到0。这实际上很好,因为这意味着脚本可以工作,只是一切都很快,它可以得到尺寸。 .load() 确保首先加载图像,然后才接收尺寸。
无论出于何种目的,你想使用尺寸,我建议在.load() 中也这样做。因为无论如何你可能会有多个.Photos a。
另外,您可能已经注意到您的.fadeIn(2000) 无法正常工作。那是因为,你的项目在你调用它之前就被附加了。如您所见,我为您修复了它:)
注意!抱歉,我重命名了一些变量(让我脑子里的东西更符合逻辑。)
【讨论】:
var MyitemWidth = item.css('width');
var MyitemHeight = item.css('height');
看到这个答案Getting auto size of IMG before adding it to DOM (Using JQuery)
DOM elements have dimensions only when added to a parent, as dimension is determined by the
rendering engine. To go around this issue, have a <div> container absolutely positioned off
screen, add the image to it first, get the dimension, then add the image at it's final destination.
【讨论】: