Posted on 2007-10-09 15:11
semovy 閱讀(4997)
評論(12) 編輯 收藏 所屬分類:
JavaScript
<html>
<head>
<title>兼容于ie,firefox,netscape的等比例圖片本地預覽的javascript實現</title>
<meta http-equie="keywords" content="兼容ie,firefox,netscape,等比例圖片,javascript">
<script type="text/javascript">
/*
兼容于ie,firefox,netscape的等比例圖片本地預覽的javascript實現
author:semovy@gmail.com
date:14:39 上午 2007-10-9
@param:targetImg string id 待顯示等比例調整過的目標元素的id字符串
@param:imgSrc string src 等處理的圖片源路徑字符串
@param:fitWidth int 等顯示圖片的最大寬度
@param:fitHeight int 等顯示圖片的最大高度
*/
function resizeImage(targetImg,imgSrc,fitWidth,fitHeight)
{
var imgSrc = "file:///" + imgSrc.replace(/\\/g,"/");//本地路徑c:\a.jpg,而ff,ns不支持,所以替換成file:///c:/a.jpg這種形式
var img = document.getElementById(targetImg);//獲取目標圖片元素容器
var tempImg = new Image();//建立臨時圖片對象
tempImg.src = imgSrc;//給臨時圖片對象賦予圖片源
var scale=1.0;//圖片度高比例因子.
var width=0,height=0;
/*firefox實現了complete屬性,而ie實現了complete屬性和readyState屬性
但是兩者對屬性的定義好像不同:
firefox: 一個圖像被下載完畢,complete屬性就是true,沒有下載完畢則為false
ie:一個圖像沒有被下載完畢,則readyState屬性為uninitialized,complete屬性是false.當下載完畢時,
readyState為complete,而如果此時圖片還沒有顯示,complete為false,顯示以后(display:block)此屬性才變成true
*/
if(document.all)//如果是ie
{
if(tempImg.readyState=='complete')
{
width = tempImg.width;//獲取源圖片寬,高
height = tempImg.height;
}
}
else(tempImg.complete)//fire fox ,netscape
{
width = tempImg.width;
height = tempImg.height;
}
scale = width/height;//寬度比例因子
if(width > fitWidth)//等比例調整
{
width = fitWidth;
height = width/scale;
if(height > fitHeight)
{
height = fitHeight;
width = height*scale;
}
}
if(height > fitHeight)
{
height = fitHeight;
width = height*scale;
}
img.width = width;//調整后的寬,高
img.height = height;
img.src = imgSrc;
img.style.display="";//顯示圖片
}
</script>
</head>
<body>
<!--目標顯示圖片組件,初始化為隱藏格式-->
<img id="img" style="display:none">
<input type="file" id="imgFile" onchange="resizeImage('img',this.value,150,150)">
</body>
</html>