简体   繁体   English

Javascript-检测图像何时加载

[英]Javascript - detect when image loaded

I have a function that, among other things, grabs a data attribute from an element and uses it for some calculations. 我有一个函数,除其他功能外,它从元素中获取data属性并将其用于某些计算。 The problem is that the attribute is assigned only once the element's background image has loaded. 问题在于,仅在加载元素的背景图像后才分配属性。

Since the function is firing before the background image has loaded, the variable I'm looking for is undefined (and therefore causing other issues). 由于该函数是在加载背景图像之前触发的,因此我要查找的变量是未定义的(因此会导致其他问题)。 I thought I would fix that by having a while loop for when the variable is undefined. 我以为我可以通过在变量未定义时使用while循环来解决此问题。 If that variable is undefined, keep checking for it until it's not: 如果变量未定义,不断检查它,直到它不是:

while ($(".element").data("ui-color") == "undefined"){
    var color = "" // keep it blank until the attribute exists
}

Then once after the loop is no longer true, assign the variable: 然后,在循环不再为真之后,分配变量:

var color = $(".element").data("ui-color");

The problem is that it seems to be disregarding the while loop and still resulting in an undefined variable. 问题在于它似乎无视while循环,但仍然导致未定义的变量。

Is there some other condition I should be using for the while loop (or some other method completely)? 我应该在while循环中使用其他条件(或完全使用其他方法)吗?

You should use JavaScript's Image.onload event, and execute the loop once the image has loaded. 您应该使用JavaScript的Image.onload事件,并在图像加载后执行循环。

Example: 例:

var img = new Image;
img.onload = function() {
  // your calculations here
}
img.src = 'path/to/file';

The onload event will fire once the image is fully downloaded and displayed by the browser. 图片完全由浏览器下载并显示后,就会触发onload事件。

Try to see in a different way, use on load event on the background image. 尝试以不同的方式查看,在背景图像上使用on load事件。 like 喜欢

$("#background").on("load",function() { console.log("blah") }

EDIT: this doesn't actually solve the problem, but instead identifies an error in the code 编辑:这实际上并不能解决问题,而是识别代码中的错误

Make this change for your code to work 进行更改以使代码正常工作

typeof $(".element").data("ui-color") == "undefined"

The typeof operator will evaluate the left-hand side to the string literal 'undefined' which is what looks like you intended to do. typeof运算符将评估字符串文字“ undefined”的左侧,这看起来像您打算执行的操作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM