4 回答

TA贡献1846条经验 获得超7个赞
你看,该函数是在图像完全加载之前调用的。我们使用其他替代方案(如Jquery就绪函数)来解决这些类型的问题。getDimensions()window.onload = function(){}
我也删除了,因为在这种情况下,我们可以只用文档调用它,它需要更少的代码,这使得脚本看起来更干净。const body=document.getElementsByTagName('body')[0];
<script>
function getDimensions(id) {
var element = document.getElementById(id);
if (element && element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
let rocketimage = new Image();
rocketimage.src ='rocketimage';
rocketimage.id ='rocketimage';
document.body.appendChild(rocketimage);
window.onload = function() {
dimentions = getDimensions('rocketimage');
console.log(dimentions);
}
</script>

TA贡献1794条经验 获得超8个赞
试试这个与设置属性,为我工作。我以这个例子从互联网上拍了一张图片。
let rocketimage=document.createElement('img');
rocketimage.setAttribute("src", "https://r-
cf.bstatic.com/images/hotel/max1024x768/186/186280585.jpg");
rocketimage.setAttribute('id','rocketimage')
const body=document.getElementsByTagName('body')[0];
body.appendChild(rocketimage);
function getDimensions(id) {
var element = document.getElementById(id);
if (element || element.tagName.toLowerCase() == 'img') {
return {
width: element.width,
height: element.height
};
}
}
// using the function on the above image:
var dims = getDimensions('rocketimage');
console.log(dims.width);
console.log(dims.height);

TA贡献1772条经验 获得超6个赞
您需要等到事件才能获得实际高度和宽度。像这样的东西会起作用。onload
const rocketimage = document.createElement('img');
// OR - const rocketimage = new Image();
rocketimage.src = 'https://images.freeimages.com/images/large-previews/e2a/boise-downtown-1387405.jpg';
rocketimage.onload = function () {
console.log('Height :', this.height);
console.log('Width :', this.width);
};
添加回答
举报