javascript - 为什么 naturalHeight 或 naturalWidth 返回 `undefined` ?

标签 javascript jquery html onload

我的类作业要我使用 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/

相关文章:

javascript - 为什么我不能在 React 中通过 ref 获取元素

Jquery 附加 div 然后使其可调整大小并可拖动?

javascript - 加载文本字段时自动调用 JS 函数

php - Zend验证码html

php - PHP 中的 PDO 函数

html - 如何在打印预览中将元素与页面底部对齐

javascript - AngularJS 错误 ng areq 不是函数

javascript - 使用 next() 填写时显示下一个输入字段

javascript - 在 jQuery ajax 函数中使用 jQuery 插件的范围问题

javascript - jquery 数据表自定义过滤器