2011-01-19 73 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;