我使用 JavaScript 动态创建 img
元素。
这些元素具有 CSS max-width
属性,因此可以调整它们的大小。
我尝试了以下代码。
function addPhoto(title, imgPath, tags) {
...
var photoImg = document.createElement('img');
photoImg.src = imgPath;
console.log(photoImg.naturalHeight);
console.log(photoImg.naturalWidth);
...
}
如果我运行上面的代码,它会打印原始图像的宽度和高度。
如何调整 img
元素的 width
和 height
大小?
最佳答案
谢谢@JonUleis!
function addPhoto(title, imgPath, tags) {
...
var photoImg = document.createElement('img');
photoImg.src = imgPath;
console.log(photoImg.height);
console.log(photoImg.width);
photoImg.onload = function() {
console.log(this.height);
console.log(this.width);
}
}
前两个 console.log
打印“undefined”。
但是,最后两个 console.log
打印 img
元素的调整大小的 width
和 height
。
关于javascript - 使用 max-width 属性获取调整后的 img 元素的宽度和高度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46182284/