JS上传图片预览 兼容IE8 FireFox
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> <style type="text/css"> #preview_wrapper { display: inline-block; width: 740px; height: 200px; background-color: #CCC; } #preview_fake { /* 该对象用户在IE下显示预览图片 */ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale); } #preview_size_fake { /* 该对象只用来在IE下获得图片的原始尺寸,无其它用途 */ filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=image); visibility: hidden; } #preview { /* 该对象用户在FF下显示预览图片 */ width: 740px; height: 200px; } </style> </head> <script type="text/javascript" language="javascript"> function onUploadImgChange(sender, p, pf, psf,width,height) { if (!sender.value.match(/.jpg|.gif|.png|.bmp/i)) //忽略大小写 { alert('图片格式无效!'); return false; } var objPreview = document.getElementById(p); //图片1 var objPreviewFake = document.getElementById(pf); //图片2 var objPreviewSizeFake = document.getElementById(psf); //外套1 if (sender.files && sender.files[0]) { objPreview.style.display = 'block'; objPreview.style.width = 'auto'; objPreview.style.height = 'auto'; objPreview.src = window.URL.createObjectURL(sender.files[0]); } else if (objPreviewFake.filters) { // IE7,IE8 在设置本地图片地址为 img.src 时出现莫名其妙的后果 //(相同环境有时能显示,有时不显示),因此只能用滤镜来解决 // IE7, IE8因安全性问题已无法直接通过 input[file].value 获取完整的文件路径 sender.select(); var imgSrc = document.selection.createRange().text; objPreviewFake.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc; objPreviewSizeFake.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = imgSrc; autoSizePreview(objPreviewFake, width, height); objPreview.style.display = 'none'; } } function autoSizePreview(objPre, originalWidth, originalHeight) { objPre.style.width = originalWidth + 'px'; objPre.style.height = originalHeight + 'px'; objPre.style.marginTop = 0 + 'px'; objPre.style.marginLeft = 0 + 'px'; } </script> <body> <div id="preview_wrapper"> <div id="preview_fake"> <img id="preview" src="" alt="" onload="autoSizePreview(this,740,200)" /> <img id="preview_size_fake" src="" alt="" /> </div> </div> <br /> <input id="upload_img" name="upload_img" type="file" onchange="onUploadImgChange(this,'preview','preview_fake','preview_size_fake',740,200)" /> </body> </html>