change image width with javascript
I'm new to javascript, and i have a qouestion about the setAttributes of an image. I want to change the width of an image depending on it's currently width. It must look something like this i think:
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
});
Li开发者_Go百科ke this it dosen't work. What's the proper way to do this?
I'm assuming that this.im
is an img
element.
Many of the things you specify as attributes but then need to interact with from JavaScript are available via reflected properties — properties on the object that reflect the value of the attribute. So:
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
For setting style stuff (including width), I'd use the style
object, so that last one would be:
this.im.style.width = curWidth + "px";
Note that style properties giving sizes must have units, just as in CSS (in this case, I've used pixels).
For any attribute that doesn't have a reflected property, use setAttribute
to set them individually:
this.im.setAttribute("foo", "bar"); // Set the `foo` attribute to `bar`
You can find out which attributes are available as reflected properties, and what other properties there are, via the W3C DOM specifications (you're looking for the HTMLImageElement
interface).
This should be enough:
var imgWidth = image.width;
image.width = imgWidth > 300 ? 300 : imgWidth;
精彩评论