开发者

Javascript onload event to resize image help

开发者 https://www.devze.com 2023-01-31 01:13 出处:网络
This might be a simple one for you guys, im learning Javascript and have hit a problem. I am trying to have the script resize a particular image on the page when onload is called like so:

This might be a simple one for you guys, im learning Javascript and have hit a problem. I am trying to have the script resize a particular image on the page when onload is called like so:

<script type="text/javascript">

 function resizeSampleImage()
 {
  document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.2;
 }

    </script>

...

<body onload = "resizeSampleImage();" >

...

<a href="http://www.buildingpeople.uk.com" target="_blank"> &l开发者_JAVA百科t;img id="sampleImage" src="Images/BP snip.jpg" alt="BuildingPeople.uk.com" /> </a>

apologies, forgot to mention that is doesn't work! after loading the page in multiple browsers the image stays it native size and the error consoles say they fail to parsing value for height. Declaration dropped.

I have tried lots of different ways but cannot seem to get it to work.


(document.body.clientWidth) * 0.2 will give you an integer. The CSS height property accepts a length.

Add some units.


There is a live example at http://jsbin.com/uyihe4

You can see the zoom effect when loading. I have only changed the

document.getElementById("sampleImage").style.height

to

document.getElementById("sampleImage").height


Well, your problem is that the images may not be ready when you apply the styles to them.

Use this function instead (note it takes a DOM object):

var imgLoader = function(domImg) {
  var imgObj = new Image();
  imgObj.onload = function() 
  {
    // apply styles
    domImg.style.height = "100px";
  }
  imgObj.src = domImg.src;
}


Though I haven't figure out the problem. But the following code snippet works for me (Tested in Chrome 8.0 and IE9.0Beta).

<html>
    <head>
        <title>test</title>
        <script type="text/javascript">
            function resizeSampleImage()
            {
                document.getElementById("sampleImage").style.height = (document.body.clientWidth) * 0.5;
            }
        </script>
    </head>
    <body onload="resizeSampleImage();">
        <img id="sampleImage" src="http://news.mydrivers.com/Img/20101217/S03405153.jpg">
    </body>
</html>
0

精彩评论

暂无评论...
验证码 换一张
取 消