2011-01-19 72 views
0

我是JavaScript新手,我對圖片的setAttributes有qouestion。 我想根據當前的寬度更改圖像的寬度。它必須看起來像這樣我認爲:使用javascript更改圖片寬度

var curWidth=this.im.width; 
if(curWidth>300) 
    curWidth=300; 
this.im.setAttributes 
({ 
    src : this.inputs['src'].value, 
    className: this.inputs['class'].value, 
    width:curWidth 
}); 

像這樣,它不工作。什麼是正確的方法來做到這一點?

+0

是什麼`this`指什麼?這是對「setAttributes()」某些庫提供的東西的調用,還是隻是一廂情願?那些「投入」價值是什麼? – Pointy 2011-01-19 14:38:51

+0

這一定是某種圖書館 – amosrivera 2011-01-19 14:39:54

回答

3

我假設this.im是一個img元素。

你們中許多人指定爲屬性,但隨後的事情需要與從JavaScript交互是通過反射特性的對象   —性質,反映了屬性值可用。所以:

var curWidth=this.im.width; 
if(curWidth>300) { // <== Added braces for clarity; purely style 
    curWidth=300; 
} 
this.im.src = this.inputs['src'].value;   // `src` is reflected 
this.im.className = this.inputs['class'].value; // `className` is the reflected "class" attribute 
this.im.width = curWidth;      // `width` is a property of its own 

對於設置風格的東西(包括寬度),我會用style對象,以便最後一個是:

this.im.style.width = curWidth + "px"; 

注意,樣式屬性賦予大小必須有單位,就像在CSS中一樣(在這種情況下,我使用了像素)。

對於不具有反射特性的任何屬性,使用setAttribute單獨設置它們:

this.im.setAttribute("foo", "bar"); // Set the `foo` attribute to `bar` 

你可以找出哪些屬性可作爲反映屬性,其他屬性也有,通過W3C DOM specifications(你正在尋找HTMLImageElement interface)。

0

這應該是足夠了:

var imgWidth = image.width; 
image.width = imgWidth > 300 ? 300 : imgWidth;