JS自动缩小图片

主要的功能是自动缩小过大的图片,以避免div构造的页面被撑坏。

本来想网上应该有现成的代码可以用,搜了半天发现,都不符合web standards标准。

于是我的洁癖心理再次发作,决定自己来写个。

现在firefox、ie、opera下通过测试,但是不知道有没有bug。

代码如下:

// 目的: 自动缩小过大的图片,避免撑坏页面
//*********************************************************
function resizeImg() {
//window.alert(’55’);
var imageAll=document.getElementById(‘content’).getElementsByTagName(‘img’);
if (imageAll !=null) {
for (i=0;i<2;i++){
if(imageAll<i>.width>380){
imageAll<i>.style.width=’380′;
imageAll<i>.onclick=function(){window.open(this.src)};
imageAll<i>.style.cursor=’hand’;
}
}
}
}

if (window.addEventListener)
window.addEventListener(‘load’, resizeImg, false);
else if (window.attachEvent)
window.attachEvent(‘onload’, resizeImg);
else
window.onload=resizeImg

另一种形式
图片自动缩小的js代码,用以防止图片撑破页面

<!–
var flag=false;
function DrawImage(ImgD){
var image=new Image();
image.src=ImgD.src;
if(image.width>0 &amp;&amp; image.height>0){
flag=true;
if(image.width/image.height>= 180/110){
if(image.width>180){
ImgD.width=180;
ImgD.height=(image.height*110)/image.width;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
/*ImgD.alt=’bigpic’ */
}
else{
if(image.height>110){
ImgD.height=110;
ImgD.width=(image.width*110)/image.height;
}else{
ImgD.width=image.width;
ImgD.height=image.height;
}
/*ImgD.alt=’bigpic’ */
}
}
}

//–>

图片使用的地方:
<img src=’图片’ border=0 width=’180′ height=’110′ onload=’javascriptrawImage(this);’>
width=’180′ height=’110′ 注意这里最好限定,如果不限定加载图时会成原大,然后再缩小,这个过程如果图大了很难看的.这里是宽度和高度,在前面的JS里改,这里也作相应的改.

图不会变形,只会按比列缩,放心

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

这个站点使用 Akismet 来减少垃圾评论。了解你的评论数据如何被处理

相关文章

开始在上面输入您的搜索词,然后按回车进行搜索。按ESC取消。

返回顶部