简体   繁体   English

Javascript onload事件以调整图像大小帮助

[英]Javascript onload event to resize image help

This might be a simple one for you guys, im learning Javascript and have hit a problem. 对于您来说,这可能是一个简单的过程,我正在学习Java脚本并遇到了问题。 I am trying to have the script resize a particular image on the page when onload is called like so: 我试图在调用onload时让脚本调整页面上特定图像的大小,如下所示:

<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"> <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. (document.body.clientWidth) * 0.2将为您提供一个整数。 The CSS height property accepts a length . CSS height属性接受一个length

Add some units. 添加一些单位。

There is a live example at http://jsbin.com/uyihe4 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): 请改用此函数(注意,它需要一个DOM对象):

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). 但是以下代码段对我有用(在Chrome 8.0和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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM