原生JS上传,实现预览并且兼容大部分IE

 1 // 前提条件: ie浏览器模式下,用户要允许ie默认的加载项;以下兼容ie的方法才会生效
 2 
 3 // 图片上传预览 IE是用了滤镜
 4 function previewImage(file) {
 5   var MAXWIDTH = 60;
 6   var MAXHEIGHT = 60;
 7   var div = document.getElementById('preview');
 8   if (file.files && file.files[0]) {
 9     div.innerHTML = '<img id=imghead>';
10     var img = document.getElementById('imghead');
11     img.onload = function () {
12       var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
13       img.width = rect.width;
14       img.height = rect.height;
15     };
16     var reader = new FileReader();
17     reader.onload = function (evt) {
18       img.src = evt.target.result;
19     };
20     reader.readAsDataURL(file.files[0]);
21     div.style.display = "inline-block";
22   } else {
23     var sFilter = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="';
24     file.select();
25     var src = document.selection.createRange().text;
26     div.innerHTML = '<img id=imghead>';
27     var img = document.getElementById('imghead');
28     img.filters.item('DXImageTransform.Microsoft.AlphaImageLoader').src = src;
29     var rect = clacImgZoomParam(MAXWIDTH, MAXHEIGHT, img.offsetWidth, img.offsetHeight);
30     status = (rect.left + ',' + rect.width + ',' + rect.height);
31     div.innerHTML = "<div id=divhead style='width:" + rect.width + "px;height:" + rect.height + "px;" + sFilter + src + "\"'></div>";
32     div.style.display = "inline-block";
33   }
34 }
35 
36 function clacImgZoomParam(maxWidth, maxHeight, width, height) {
37   var param = {top: 0, left: 0, width: width, height: height};
38   if (width > maxWidth || height > maxHeight) {
39     rateWidth = width / maxWidth;
40     rateHeight = height / maxHeight;
41 
42     if (rateWidth > rateHeight) {
43       param.width = maxWidth;
44       param.height = Math.round(height / rateWidth);
45     } else {
46       param.width = Math.round(width / rateHeight);
47       param.height = maxHeight;
48     }
49   }
50 
51   param.left = Math.round((maxWidth - param.width) / 2);
52   param.top = Math.round((maxHeight - param.height) / 2);
53   return param;
54 }

 

转载于:https://www.cnblogs.com/myclovers/p/5842930.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值