Tuesday, January 17, 2012

Javascript: setting image width/height in pixels, cannot use "px"


The *img* element has its own width and height property. You can resize an image by setting its width and height property or by setting its style property, e.g.

   imageElement.width = "100";
      or
   imageElement.style.width = "100px";

They both resize the width of the image to 100 pixels.

You may notice that one is set with "px" at the end, the other is without. If you try the following code, you can find "px" is not needed in the 3rd case:

<html>
<head>
<script type="text/javascript">
function changeSize1()
{
  document.getElementById("b1").style.width="300px";
  document.getElementById("b1").style.height="300px";
}
function changeSize2()
{
  document.getElementById("b2").style.width="300";
  document.getElementById("b2").style.height="300";
}
function changeSize3()
{
  document.getElementById("b3").width="300px";
  document.getElementById("b3").height="300px";
}
function changeSize4()
{
  document.getElementById("b4").width="300";
  document.getElementById("b4").height="300";
}
</script>
</head>
<body>

Click the image to change size. <br /><br />
image 1: <img id="b1" onclick="changeSize1()" src="" /><br />
image 2: <img id="b2" onclick="changeSize2()" src="" /><br />
image 3: <img id="b3" onclick="changeSize3()" src="" /><br />
image 4: <img id="b4" onclick="changeSize4()" src="" /><br />

</body>
</html>

The code of the 3rd function:

  document.getElementById("b3").width="300px";
  document.getElementById("b3").height="300px";

will cause the size of the image becomes 0. "px" cannot be used with the width/height property of *img*.

No comments:

 
Get This <