改变图像的大小与JavaScript

我正在尝试使用JavaScript更改图片的大小。 jS文件与HTML页面是分开的。

我想在JS文件中设置图像的高度和宽度。 任何好的方法呢?

一旦你有一个对你的形象的引用,你可以像这样设置它的高度和宽度:

var yourImg = document.getElementById('yourImgId'); if(yourImg && yourImg.style) { yourImg.style.height = '100px'; yourImg.style.width = '200px'; } 

在html中,它看起来像这样:

 <img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/> 

您可以像这样更改实际的宽度/高度属性:

 var theImg = document.getElementById('theImgId'); theImg.height = 150; theImg.width = 150; 

如果要在加载后调整图像大小,可以将其附加到<img>标签的onload事件上。 请注意,它可能不支持所有的浏览器( 微软的参考声明,它是HTML 4.0规范的一部分,但HTML 4.0规范没有列出<img>onload事件)。

下面的代码已经过testing和工作:IE 6,7和8,Firefox 2,3和3.5,Opera 9和10,Safari 3和4以及Google Chrome:

 <img src="yourImage.jpg" border="0" height="real_height" width="real_width" onload="resizeImg(this, 200, 100);"> <script type="text/javascript"> function resizeImg(img, height, width) { img.height = height; img.width = width; } </script> 

更改图像很简单,但如何在更改后将其更改回原始大小? 您可以尝试将文档中的所有图像更改为原始大小:

 var i,L = document.images.length;
对于(I = 0; I <L,++ⅰ){
  document.images [i] .style.height ='auto';  //设置CSS值
  document.images [i] .style.width ='auto';  //设置CSS值
 // document.images [i] .height ='';  (不需要这个,会设置img.attribute)
 // document.images [i] .width ='';  (不需要这个,会设置img.attribute)
 }

您可以在这里看到结果在这些简单的代码块中,您可以更改图像的大小,并在鼠标进入图像时使其更大,并且在离开时它会恢复到原始大小。

HTML:

 <div> <img onmouseover="fifo()" onmouseleave="fifo()" src="your_image" width="10%" id="f" > </div> 

js文件:

 var b=0; function fifo() { if(b==0){ document.getElementById("f").width = "300"; b=1; } else { document.getElementById("f").width = "100"; b=0; } } 
 // This one has print statement so you can see the result at every stage if you would like. They are not needed function crop(image, width, height) { image.width = width; image.height = height; //print ("in function", image, image.getWidth(), image.getHeight()); return image; } var image = new SimpleImage("name of your image here"); //print ("original", image, image.getWidth(), image.getHeight()); //crop(image,200,300); print ("final", image, image.getWidth(), image.getHeight());