且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

载入图片后,Javascript计算图片大小

更新时间:2022-01-16 07:08:51

这没有道理:

img.onLoad = loader(img);

您要将实际功能传递给事件:

you want to pass the actual function to the event:

img.onload = loader;

,然后在函数中使用this代替img.

and use this instead of img within the function.

此外,您还需要在更改图像的src属性之前,先分配事件.

Also you need to assign the event before changing the image's src property.

还请注意,图像上的load事件存在许多问题.摘自有关load()的jQuery手册:

Also note that there are numerous problems with the load event on images. From the jQuery manual on load():

与图片一起使用时的加载事件提示

Caveats of the load event when used with images

开发人员试图使用.load()快捷方式解决的一个常见挑战是,在完全加载图像(或图像集合)后执行函数.有几个已知的注意事项,应该注意.这些是:

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

  • 它不能始终如一地工作,也不能可靠地跨浏览器
  • 如果图像src设置为与以前相同的src,则无法在WebKit中正确触发
  • 它不能正确地使DOM树冒泡
  • It doesn't work consistently nor reliably cross-browser
  • It doesn't fire correctly in WebKit if the image src is set to the same src as before
  • It doesn't correctly bubble up the DOM tree