我目前正在获取each()语句中的一些图像的大小。
我正在将一个函数绑定到它的load事件。不过,在继续执行代码之前,我需要它来获取图像的高度。
$(window).load(function () {
$("element").each( function() {
/*
.
.
.
.
*/
var containerHeight = $(this).height();
var imgHeight = 0;
//get the size of the full image.
var imgLoad = $("<img />");
imgLoad.attr("src", imgSrc);
imgLoad.bind("load", function () { imgHeight = this.height; });
heightDiff = (imgHeight - containerHeight);
//some methods are called...
//imgHeight is still set to 0
});
});我考虑过使用.trigger("custom-event")
然后检查它是否是用Jquery的.when()方法调用的
但是,有没有更简单(如果不是更好)的方法来做这件事呢?
致以敬意,
发布于 2015-05-08 15:20:49
非常经典的"how can I return values from an asynchronous function"问题。
你不能,句号。使用回调。
$("element").each(function () {
var containerHeight = $(this).height(),
imgSrc = "something";
$("<img />", { src: imgSrc })
.appendTo("#whatever")
.on("load", function () {
var $img = $(this),
heightDiff = ($img.height() - containerHeight);
//some methods are called...
});
});发布于 2015-05-08 15:09:31
我认为你做的几乎是正确的,当所有的元素(包括图片)被加载时,window.load被触发。要获取每个图像的高度,请使用如下命令:
$(window).load(function(){
// triggered when images are loaded
$('img').each(function() {
// get the height of each image
var height = $(this).height();
});
});发布于 2015-05-08 15:33:00
您不能协商图像加载是同步完成的,所以您必须在load事件回调函数中完成所有工作:
var imgLoad = new Image();
imgLoad.onload = function() {
var imgHeight = this.height,
heightDiff = (imgHeight - containerHeight);
// do stuff here
};
imgLoad.src = imgSrc; // load imagehttps://stackoverflow.com/questions/30117654
复制相似问题