javascript - 从 JavaScript Image Onload 函数获取图像宽度值

标签 javascript onload

我有以下获取给定图像宽度的方法:

<!DOCTYPE html>
<html>
<head>
    <title>Image Width</title>
    <script>
        var img = new Image();
        img.onload = function() { 
            alert("Width: " + img.width);
        };
        img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"

        // Do something with 'img.width' here, outside the image onload event handler.

    </script>
</head>
<body>
</body>
</html> 

我知道我需要在获取图像宽度之前加载图像,以及如何从图像 onload 事件处理程序中获取其宽度,但我在从 访问其宽度时遇到了真正的困难em>在处理程序之外

我只是个白痴,错过了一些非常简单的东西还是它比我想象的更复杂?

任何帮助将不胜感激。

问候,史蒂夫。

最佳答案

您面临的问题是异步编程。 onload函数稍后会被引擎调用,程序将暂停执行。

有两个选项:

  1. 如果您需要尽快获得该值,则必须运行 onload 中的代码,例如:

    var img = new Image();
    img.onload = function() { 
        alert("Width: " + img.width);
        // Do something with 'img.width' here, outside the image onload event handler.
    };
    img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
    
  2. 如果访问 img.width 的代码稍后发生,例如用户点击某些内容后,您可以存储该值并在其他地方使用它:

    var width;
    
    var img = new Image();
    img.onload = function() { 
        width = img.width;
    };
    img.src="http://www.hq.nasa.gov/office/pao/History/alsj/misc/apmisc-60-SAT-1.jpg"
    
    function anotherFunction() {
        alert(width);
    }
    

关于javascript - 从 JavaScript Image Onload 函数获取图像宽度值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60571105/

相关文章:

javascript - 为什么我不能将 undefined 分配给 window.load?

jQuery .ready() 用于信息路径表单?

javascript - onload 和 onclick 等效吗?

javascript - 开始 html 页面滚动

javascript - <a> onload 的替代方案是什么?

javascript - 用于显示导航的动画网页

c# - 全局变量丢失导致函数分配失败

javascript - 自定义force.drag会在悬停时丢失粘性节点

javascript - 如何在同一页面上多次使用 windows.onload 或 a.click 等事件监听器?

javascript - 当其他事件处于事件状态时停止 DOM 事件?