使用JavaScript更改图像大小

Spy*_*n02 46 javascript image

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

我想在JS文件中设置图像的高度和宽度.这样做有什么好方法吗?

Pat*_*Pat 66

一旦您有了对图像的引用,就可以设置它的高度和宽度,如下所示:

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

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

<img src="src/to/your/img.jpg" id="yourImgId" alt="alt tags are key!"/>
Run Code Online (Sandbox Code Playgroud)


Col*_*ell 17

您可以更改实际的宽度/高度属性,如下所示:

var theImg = document.getElementById('theImgId');
theImg.height = 150;
theImg.width = 150;
Run Code Online (Sandbox Code Playgroud)

  • 如果通过CSS设置图像的宽度和高度,似乎不起作用 (3认同)

Gra*_*ner 6

如果要在加载图像后调整图像大小,可以附加到标记的onload事件<img>.请注意,并非所有浏览器都支持它(Microsoft的参考声明它是HTML 4.0规范的一部分,但HTML 4.0规范没有列出onload事件<img>).

下面的代码经过测试和工作:IE 6,7和8,Firefox 2,3和3.5,Opera 9和10,Safari 3和4以及谷歌浏览器:

<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>
Run Code Online (Sandbox Code Playgroud)


小智 5

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

var i,L=document.images.length;
for(i=0;i<L;++i){
 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)
}