admin管理员组

文章数量:1415111

I want to make a picture constantly but cannot seem to find relevant results. For instance, I have a picture of 50px (width) by 100px (height) and I want to change the width from 25px to 100px and the height from 50px to 200px (so image stays width divided by height).

How would I do that and is it possible (I guess it is)?

Here a the basic code:

HTML

<div id="container">
<div class="image"><img src=".jpg" width="50px" height="100px"/></div>
</div>

CSS

div#container {
    width: 100%;
    height: 100%;
}

div.image {
    position:fixed;
}

Fiddle

I want to make a picture constantly but cannot seem to find relevant results. For instance, I have a picture of 50px (width) by 100px (height) and I want to change the width from 25px to 100px and the height from 50px to 200px (so image stays width divided by height).

How would I do that and is it possible (I guess it is)?

Here a the basic code:

HTML

<div id="container">
<div class="image"><img src="http://lib/files/images/library/black-square.jpg" width="50px" height="100px"/></div>
</div>

CSS

div#container {
    width: 100%;
    height: 100%;
}

div.image {
    position:fixed;
}

Fiddle

Share Improve this question edited Oct 27, 2013 at 8:15 PMint asked Oct 27, 2013 at 7:48 PMintPMint 2462 silver badges13 bronze badges 0
Add a ment  | 

3 Answers 3

Reset to default 2

To change the size immmediately, you can just set the CSS style with javascript:

var img = document.querySelectorAll("#container .image img")[0];

img.style.height = "200px";
img.style.width = "100px";

Demo: http://jsfiddle/jfriend00/bh94J/


If you want the size to change gradually, you can use CSS3 by also specifying this CSS:

.image img {
   -moz-transition: height 3s, width 3s;
    -webkit-transition: height 3s, width 3s;
    transition:  height 3s, width 3s;
}

as seen in this demo: http://jsfiddle/jfriend00/6YTmt/

see the demo here: http://jsfiddle/jELqu/4/

Use <yourImg>.style.height and <yourImg>.style.width for setting new values.

You can call a function to do the scaling. For example:

if you would like to re-size the picture to the width of 200 pixels and height 300 pixels you could do something like this:

first create a function, let's name it function scale(e). This function will get a parameter which is the image object you want to re-scale.

At the function we can get the style property of the image object and change the width and height as you can see below.

Now we need to call the function and provide the image object like this: onclick="scale(this);"

The full code:

<div id="container">
<div class="image" ><img src="http://lib/files/images/library/black-square.jpg" width="50px" height="100px" onclick="scale(this);"/></div>

and the function itself:

function scale(e) {
   e.style.width="200px";
   e.style.height="300px";
}

本文标签: javascriptDynamically change image sizeStack Overflow