我正嘗試調整基於最大寬度/最大高度數組的圖像大小。下面是我想出迄今:調整大小後獲取圖像大小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