瀏覽器廠商不同,實(shí)現(xiàn)某種特定功能需要進(jìn)行兼容處理,如圖片預(yù)覽跪呈,主流瀏覽器支持html5
FileReader
,但是IE就****
1.FileReader
目前為止取逾,firefox3.6+耗绿、 chrome6+、 Safari5.2+砾隅、 Opera11+误阻、及IE10瀏覽器支持FileReader對象。
用法:
html
<input type="file" id="myfile">
<img src="" id="img" alt="">
js
<script>
ipt.onchange=function(){
var f=new FileReader();//獲取FileReader實(shí)例對象
f.readAsDataURL(myfile.files[0]);//讀取圖片base64數(shù)據(jù)
f.onload=function(){//讀取完畢將結(jié)果賦值對象img src
img.src=this.result;
}
}
</script>
IE處理方式
比較欣慰的是IE中file
表單可以獲取選中圖片的絕對路徑,不要急究反,有絕對路徑了寻定,確不能直接賦值給img,因?yàn)槌薎E6之外精耐,由于安全問題直接設(shè)置img的src無法顯示本地圖片狼速,但是可以通過濾鏡來實(shí)現(xiàn):
非IE6
myfile.select();
myfile.blur();
var reallocalpath = document.selection.createRange().text;
img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src="" + reallocalpath + "")";
// 設(shè)置img的src為base64編碼的透明圖片 取消顯示瀏覽器默認(rèn)圖片
img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
IE6
myfile.select();
myfile.blur();
var reallocalpath = document.selection.createRange().text;
img.src=reallocalpath;
兼容處理完整代碼
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="file" id="myfile">
<img src="" id="img" alt="">
</body>
<script>
myfile.onchange=function(){
if(window.FileReader){
var f=new FileReader();
f.readAsDataURL(myfile.files[0]);
f.onload=function(){
img.src=this.result;
}
}else{
var isIE = navigator.userAgent.match(/MSIE/)!= null,
isIE6 = navigator.userAgent.match(/MSIE 6.0/)!= null;
if(isIE) {
myfile.select();
myfile.blur();
var reallocalpath = document.selection.createRange().text;
// IE6瀏覽器設(shè)置img的src為本地路徑可以直接顯示圖片
if (isIE6) {
img.src = reallocalpath;
}else {
// 非IE6版本的IE由于安全問題直接設(shè)置img的src無法顯示本地圖片,但是可以通過濾鏡來實(shí)現(xiàn)
img.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod='scale',src="" + reallocalpath + "")";
// 設(shè)置img的src為base64編碼的透明圖片 取消顯示瀏覽器默認(rèn)圖片
img.src = 'data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==';
}
}
}
}
</script>
</html>
加油卦停!