javascript - 如何在 Javascript 中收到图像尺寸可用的提醒?

标签 javascript dom-events onload image-loading

我需要能够等到图像的高度和宽度可用时才启动函数。当此代码调用 start() 时,它仍然表示高度和宽度为零:

var img = new Image();

init = function() {
    img.onload = this.start();
    img.src = "sky.jpg";
    }

start = function() {
    alert("Start called.\nwidth:"+img.width+"\nheight"+img.height);
    }

init();

如何让它等到维度可用后再调用 start()

最佳答案

var img = new Image();

var start = function() {
    alert("Start called.\nwidth:"+img.width+"\nheight"+img.height);
}

var init = function() {
    img.onload = start;
    img.src = "sky.jpg";
} 

init();

this.start() 更改为 start

我还确定了您的功能范围。

关于javascript - 如何在 Javascript 中收到图像尺寸可用的提醒?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4341796/

相关文章:

javascript - Reveal-modal 出现后如何调用函数

javascript - 在不丢失事件监听器的情况下克隆Node

javascript - 使元素对用户可见但对事件不可见

javascript - 一个好的跨浏览器 "ready"事件不使用 jQuery?

jquery - 单击使用 jQuery 加载的链接

javascript - 未捕获的类型错误 : this. props.onDelete 不是函数 reactjs

javascript - 在 AngularJS 中加载时隐藏模板

javascript - 需要对以下代码进行哪些更改才能设置 jQuery slider 的滑动暂停时间?

javascript - 开发人员工具具有初始焦点,可防止键盘事件而无需先单击文档

javascript - JScript : How can I throw an error message when image is not loaded?