2009-08-19 542 views

回答

54

一旦你有你的形象的參考,你可以設置它的高度和寬度,像這樣:

var yourImg = document.getElementById('yourImgId'); 
if(yourImg && yourImg.style) { 
    yourImg.style.height = '100px'; 
    yourImg.style.width = '200px'; 
} 

在HTML,它應該是這樣的:

<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/> 
+0

你必須在頁面加載完成後,確保執行的JavaScript。您可以通過將其放入onload事件中,或將腳本放在頁面的底部,即在關閉body標籤之前執行此操作。 – Pat 2009-08-19 02:32:03

+0

啊,現在作品謝謝。 – Spyderfusion02 2009-08-19 02:48:13

+0

更改樣式後沒有任何方法更改'yourImage.height = 100'的實際高度,並且沒有裁剪圖像? – Squirrl 2014-03-07 08:41:00

16

您可以更改實際的寬度/高度屬性是這樣的:

var theImg = document.getElementById('theImgId'); 
theImg.height = 150; 
theImg.width = 150; 
+2

如果圖像的寬度和高度是通過CSS設置的,似乎不起作用 – szx 2013-11-06 14:04:30

6

如果你想調整圖像的大小後加載,你可以att例如<img>標記的onload事件。請注意,它可能不被所有瀏覽器支持(Microsoft's reference聲稱它是HTML 4.0規範的一部分,但HTML 4.0 spec未列出<img>onload事件)。

下面的代碼進行測試和工作在:IE 6,7 & 8,火狐2,3 & 3.5,歌劇9 & 10,Safari瀏覽器3 & 4和谷歌瀏覽器:

<img src="yourImage.jpg" border="0" height="real_height" width="real_width" 
    onload="resizeImg(this, 200, 100);"> 

<script type="text/javascript"> 
function resizeImg(img, height, width) { 
    img.height = height; 
    img.width = width; 
} 
</script> 
4

更改圖像很容易,但如何在更改後將其更改回原始大小?你可以試試這個改變所有圖像文檔中回原來的大小:

 
var i,L=document.images.length; 
for(i=0;i<L;++i){ 
document.images[i].style.height = 'auto'; //setting CSS value 
document.images[i].style.width = 'auto'; //setting CSS value 
// document.images[i].height = ''; (don't need this, would be setting img.attribute) 
// document.images[i].width = ''; (don't need this, would be setting img.attribute) 
} 
0
// This one has print statement so you can see the result at every stage if  you would like. They are not needed 

function crop(image, width, height) 
{ 
    image.width = width; 
    image.height = height; 
    //print ("in function", image, image.getWidth(), image.getHeight()); 
    return image; 
} 

var image = new SimpleImage("name of your image here"); 
//print ("original", image, image.getWidth(), image.getHeight()); 
//crop(image,200,300); 
print ("final", image, image.getWidth(), image.getHeight()); 
+3

嘗試描述你在回答中做什麼,而不是僅僅粘貼裸露的源代碼。如果你這樣做,它幾乎總能幫助提問者。 – 2016-08-16 01:19:04

2

you can see the result here 在這些代碼簡單的塊,你可以改變圖片的大小,使之更大時鼠標在圖像上方輸入,當鼠標離開時它會恢復到原始大小。

HTML:

<div> 
<img onmouseover="fifo()" onmouseleave="fifo()" src="your_image" 
     width="10%" id="f" > 
</div> 

js文件:

var b=0; 
function fifo() { 
     if(b==0){ 
      document.getElementById("f").width = "300"; 
      b=1; 
      } 
     else 
      { 
     document.getElementById("f").width = "100"; 
      b=0; 
     } 
    }