js上传图片预览的实现方法
程序员文章站
2022-10-31 13:23:04
本文实例为大家分享了js上传图片预览的方法,供大家参考,具体内容如下
本文实例为大家分享了js上传图片预览的方法,供大家参考,具体内容如下
<html > <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <title>图片上传本地预览</title> <style type="text/css"> #preview{width:260px;height:190px;border:1px solid #000;overflow:hidden;} #imghead {filter:progid:dximagetransform.microsoft.alphaimageloader(sizingmethod=image);} </style> <script type="text/javascript"> //图片上传预览 ie是用了滤镜。 function previewimage(file) { var maxwidth = 260; var maxheight = 180; var div = document.getelementbyid('preview'); if (file.files && file.files[0]) { div.innerhtml ='<img id=imghead>'; var img = document.getelementbyid('imghead'); img.onload = function(){ var rect = clacimgzoomparam(maxwidth, maxheight, img.offsetwidth, img.offsetheight); img.width = rect.width; img.height = rect.height; // img.style.marginleft = rect.left+'px'; img.style.margintop = rect.top+'px'; } var reader = new filereader(); reader.onload = function(evt){img.src = evt.target.result;} reader.readasdataurl(file.files[0]); } else //兼容ie { var sfilter='filter:progid:dximagetransform.microsoft.alphaimageloader(sizingmethod=scale,src="'; file.select(); var src = document.selection.createrange().text; div.innerhtml = '<img id=imghead>'; var img = document.getelementbyid('imghead'); img.filters.item('dximagetransform.microsoft.alphaimageloader').src = src; var rect = clacimgzoomparam(maxwidth, maxheight, img.offsetwidth, img.offsetheight); status =('rect:'+rect.top+','+rect.left+','+rect.width+','+rect.height); div.innerhtml = "<div id=divhead style='width:"+rect.width+"px;height:"+rect.height+"px;margin-top:"+rect.top+"px;"+sfilter+src+"\"'></div>"; } } function clacimgzoomparam( maxwidth, maxheight, width, height ){ var param = {top:0, left:0, width:width, height:height}; if( width>maxwidth || height>maxheight ) { ratewidth = width / maxwidth; rateheight = height / maxheight; if( ratewidth > rateheight ) { param.width = maxwidth; param.height = math.round(height / ratewidth); }else { param.width = math.round(width / rateheight); param.height = maxheight; } } param.left = math.round((maxwidth - param.width) / 2); param.top = math.round((maxheight - param.height) / 2); return param; } </script> </head> <body> <div id="preview"> <img id="imghead" width=100 height=100 border=0 src='<%=request.getcontextpath()%>/images/defaul.jpg'> </div> <input type="file" onchange="previewimage(this)" /> </body> </html>
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持。