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)
如果要在加载图像后调整图像大小,可以附加到标记的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) }