我的类作业要我使用 defer
我正在引用的脚本的标记,但这会导致图像的 naturalWidth
由于我的 js 文件中的执行顺序而未定义。
我的 HTML 头部有这一行(作业要我把它放在 <head>
但使用 defer="defer"
)
<script src="scripts/script.js" defer="defer"></script>
我的代码:
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
之前运行实际上发生了。这是否意味着我是分配 birdImage.width
的奴隶?在function
范围内的 catImage.onload
?
附言我尝试了 catImage.onload = () => { //block of code }
的 ES6但这似乎不起作用。
最佳答案
问题是您正在尝试访问超出范围的变量。
请试一试:
<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>
关于javascript - 为什么 naturalHeight 或 naturalWidth 返回 `undefined` ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44480034/