为什么 naturalHeight 或 naturalWidth return `undefined`?

Why does naturalHeight or naturalWidth return `undefined`?

我的 class 任务要求我为我引用的脚本使用 defer 标签,但这导致图像的 naturalWidth 由于执行顺序而未定义我的 js 文件。

我的 HTML 头部有这一行(作业要我把它放在 <head> 但使用 defer="defer"<script src="scripts/script.js" defer="defer"></script>

我的 js:

var catImageWidth = document.getElementById("cat-image").naturalWidth;
var birdImage = document.getElementById("bird-image");
birdImage.width = catImageWidth;

所以我尝试了这个:

var catImage = document.getElementById("cat-image");
var birdImage = document.getElementById("bird-image");
var catImageWidth;

catImage.onload = function() {
    catImageWidth = this.naturalWidth;
    console.log(catImageWidth) //logs 600
}

birdImage.width = catImageWidth; //logs `undefined`

我认为 birdImage.width 的赋值是未定义的,因为这行代码在 catImage.onload 实际发生之前运行。这是否意味着我在 catImage.onloadfunction 范围内分配 birdImage.width

P.S。我尝试了 catImage.onload = () => { //block of code } 的 ES6,但这似乎不起作用。

Does this mean that I'm slave to assigning birdImage.width within the scope of the function of catImage.onload?

看来是这样,这是最好的方法。

您可以使用箭头函数,但不能使用 this 关键字来引用图像。

无效:

catImage.onload = () => {
    catImageWidth = this.naturalWidth; //undefined
    console.log(catImageWidth)
}

因为在箭头函数中 this 对象没有绑定到图像引用,它引用了外部作用域的 this.

有效:

catImage.onload = function() {
    catImageWidth = this.naturalWidth;
    console.log(catImageWidth) //logs 600
}

或:

catImage.onload = function() {
    catImageWidth = catImage.naturalWidth;
    console.log(catImageWidth) //logs 600
}

问题是您正试图访问超出范围的变量。

请试一试:

<img id="cat-image" src="https://static.pexels.com/photos/104827/cat-pet-animal-domestic-104827.jpeg">
<img id="bird-image" src="http://animalia-life.club/data_images/bird/bird3.jpg">

<script>
var catImage = document.getElementById("cat-image");
var birdImage = document.getElementById("bird-image");
var catImageWidth;

catImage.onload = function() {
    catImageWidth = this.naturalWidth;
    birdImage.width = catImageWidth;
}

console.log(birdImage.width);
</script>