我是javascript的新手,我对图像的setAttributes有一个问题。 我想根据它当前的宽度来改变图像的宽度。它必须看起来像我想的那样:
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 :(得分: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),您可以找到哪些属性可用作反映属性,以及有哪些其他属性。
答案 1 :(得分:0)
这应该足够了:
var imgWidth = image.width;
image.width = imgWidth > 300 ? 300 : imgWidth;