Javascript计算图像大小,图像加载后

标签 javascript jquery image onload wait

function loader(img) {
        var imgH = img.height;
        var imgW = img.width;
        console.log(imgH, imgW);    
    };

img = new Image();
img.src ='../images/pic1.jpeg';
img.onLoad = loader(img);

所以,它是 exepeted,我将获得图像的大小,但我在控制台中得到“0 0”。图像大小为 500X700。这段代码有什么问题?

最佳答案

这是没有意义的:

img.onLoad = loader(img);

您想将实际函数传递给事件:

img.onload = loader;

并在函数中使用 this 而不是 img

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

另请注意,图像上的加载事件存在许多问题。来自jQuery manual on load():

Caveats of the load event when used with images

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:

  • 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

关于Javascript计算图像大小,图像加载后,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7267663/

相关文章:

javascript - 如何向具有多个加载器的 webpack 加载器添加查询?

javascript - React - 如何渲染嵌套组件而不是 [object Object]?

image - Golang io.Reader 问题与 jpeg.Decode 返回 EOF

JQuery validator.addMethod 使用类名验证复选框

JQuery - 多选选项

html - 将图像粘贴到 div 的中心

html - 将图像向下推的CSS问题

javascript - z 索引为 : 9999 being hidden by iframe with z-index: -1 IE8- 的 Div

javascript - 在 Bootstrap 模式中提交表单

jquery - 使用 jQuery Address 处理深度链接的正确方法