我有以下获取给定图像宽度的方法:
<!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
函数稍后会被引擎调用,程序将暂停执行。
有两个选项:
如果您需要尽快获得该值,则必须运行
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"
如果访问
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/