【发布时间】:2026-01-31 08:15:02
【问题描述】:
我有一个名为 PhotoTags 的类,它有一个名为 getScalePercent() 的函数。在 getScalePercent 中,我做了一个简单的计算,涉及显示图像的宽度和高度,并返回一个值。在 PhotoTags 的渲染函数中,我使用坐标数据在照片上应用元素。仅当图像已 100% 加载时,此逻辑才能正常工作。如果我刷新页面足够多次,我可以看到我的逻辑实际上是在正确设置坐标,但只有在图像被缓存或快速加载后。因此,我想使用 imagesLoaded 来检查图像是否已加载,以便有效地使用坐标。
我的函数如下所示:
getScalePercent(){
var p =0;
var targetWidth = $('.expanded-image').width();
var targetHeight = $('.expanded-image').height();
p = (targetWidth / 1920);
return p;
}
在我的渲染函数中,我尝试使用 imagesLoaded 来检查在使用 getScalePercent() 之前是否已加载图像:
render(){
var p = 0;
$('.expanded-image').imagesLoaded().done( function() {
p = this.getScalePercent();
});
console.log(p); //But value is still 0
//I then want to use p later in the render function
我的变量 p 没有在 imagesLoaded 的 .done 事件中进行操作。我知道它与异步调用有关,但我尝试将 imagesLoaded 放入 getScalePercent() 但无济于事。我还尝试对 getScalePercent() 和许多其他变体进行回调,但仍然无济于事。基本上我想做的是在 imagesLoaded 的 .done() 事件中触发 getScalePercent()。然后我希望能够在 PhotoTags 的渲染函数中使用 getScalePercent() 返回的值(当图像完全加载时)。非常感谢任何帮助。
【问题讨论】:
-
因此您必须在
done回调中使用p设置您的逻辑,或者从中调用一个将p作为参数传递的函数
标签: javascript jquery reactjs jquery-deferred imagesloaded