我的班级作业希望我对我引用的脚本使用
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
实际发生之前运行。这是否意味着我是在 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>
这是否意味着我是在
的函数范围内分配birdImage.width
的奴隶?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
}
使用 JQuery 也可以(请注意,我首先保存元素引用(我正在使用维护此元素的 JS 类),然后我需要正确获取在
naturalWidth
中保存
onLoad
的对象功能:
构建 DOM 后获取参考:
this._imageElement = $(this._htmlElement).find("img.theImage:first");
$(this._imageElement).on('load', this._onImageLoaded.bind(this));
后者:
_onImageLoaded() {
this._imageWidth = this._imageElement[0].naturalWidth;
this._imageHeight = this._imageElement[0].naturalHeight;
}