我正尝试调整基于最大宽度/最大高度数组的图像大小。下面是我想出迄今:调整大小后获取图像大小JavaScript
<html>
<head>
<title>Image resize test</title>
<script>
function createImage(){
//The max-width/max-height
var maxDim = [500,500];
//Create the image
var img = document.createElement("img");
img.setAttribute("src","http://nyrixcorp.com/images/eggplant_service.png");
document.body.appendChild(img);
//Function for resizing an image
function resize(){
//resize the image
var portrait = this.width < this.height;
this[portrait ? "height" : "width"] = maxDim[portrait ? 1 : 0];
//What is the height? PROBLEM HERE!!!
console.log(this.height);
}
//Is the image loaded already?
var temp = new Image();
temp.src = img.src;
var loaded = typeof temp.complete != "undefined" ? temp.complete : !isNaN(temp.width+temp.height) && temp.width+temp.height != 0;
//Fire the resize function
if (loaded) resize.call(img);
else img.addEventListener("load",resize,false);
}
</script>
</head>
<body onload="createImage()">
</body>
</html>
您应该能够运行这个文件原样。它可以在加载图像后获得宽度/高度。但是一旦你改变了宽度,它仍然记录旧的高度。唯一正常工作的浏览器似乎是Firefox(新版本)。所有其他浏览器在窗口完成加载之前不更新高度属性。
有没有人知道这个问题的解决办法?该图像已经加载,但它没有给出正确调整大小的尺寸。
在Chrome上正常工作14.0.835.187m – lostyzd
我使用的是Chrome 13,它在第一次加载页面时起作用。但是,刷新时,它会给出错误的高度。 – Azmisov
@Azmisov它是如何改变高度为160的情况下,FF和铬没有看到任何东西写在你的代码... – Varun