您的位置:首页 > Web前端 > HTML5

HTML5图片拖拽预览原理及实现

2016-12-12 10:34 573 查看

一、前言

这两天恰好有一位同事问我怎样做一个图片预览功能。作为现代人的我们首先想到的当然是HTML5啦,其实HTML5做图片预览已经是一个老生常谈的问题了。我在这里就简单说说其中相关的一些东西,当然会附上我们的源码。在 HTML5 之前我们做图片预览主流做法有两种,第一种是通过 Flash 插件来做预览,第二种是 Ajax 实现的假预览,也就是说选择图片文件后,图片其实已经异步上传到服务器,服务器处理后返回图片路径,前端得到响应结果做出处理从而使图片显示在界面上。而有了 HTML5 之后就可以强烈鄙视上面两种做法了。

二、FileReader

要做图片预览功能,就不得不介绍一下 FileReader,顾名思义,它是用来读取文件的。当然新东西总会有一些顽固派排斥的,我们先来看看其兼容性如何(这不是本文讨论的重点)。

PC端兼容列表

<!DOCTYPE html>
<html>
<head>
<title>Cboyce-HTML5图片预览</title>
<style type="text/css">
body{
font-family: '微软雅黑';
}
/*主容器*/
.container{
width: 90%;
margin-top: 20px;
}
/*每一个图片预览项容器*/
.img-prev-item{
width: 200px;
height: 200px;
display: inline-block;
border:1px solid #ccc;
text-align: center;
border-radius: 3px;
}
/*图片预览容器*/
.container .img-prev-container{
width: 200px;
height: 156px;
margin: 0 auto;
border-bottom: 1px solid #ccc;
vertical-align: middle;
display: table-cell;
padding: 2px;
color: #838383;
text-align: center
}
/*预览图片样式*/
.container .img-prev-container img{
width: 100%;
height: auto;
max-height: 100%;
}
/*label*/
.selfile{
background-color: #0095ff;
color: white;
padding: 6px 58px;
border-radius: 5px;
}
/*工具条 div*/
.tool{
padding-top: 9px;
}
/*隐藏文件选择器*/
#fileSelecter{
display: none;
}
</style>
</head>
<body>
<div class="container">
<div class="img-prev-item">
<div class="img-prev-container" id="img-perv-div">
请选择图片或者<br />将图片拖拽至此
</div>
<div class="tool">
<label for="fileSelecter" class="selfile">请选择图片</label>
<input type="file" value="请选择图片" id="fileSelecter" />
</div>
</div>
</div>
<script type="text/javascript">
window.onload = function(){

//预览图的容器
var _img_container = getDomById('img-perv-div')
//创建reader对象
var reader = new FileReader();

//触发 change 事件
getDomById('fileSelecter').onchange = function(event){
//获取文件对象
var file = event.target.files[0];

//读取完成后触发
reader.onload = function(ev){
//获取图片的url
var _img_src = ev.target.result;
//添加预览图片到容器框
showPrevImg(_img_container,_img_src);
}
//获取到数据的url 图片将转成 base64 格式
reader.readAsDataURL(file);
}

//添加拖放支持
_img_container.addEventListener('dragover',function(ev){
//ev.stopPropagation();
ev.preventDefault();//阻止默认事件。比如说Chrome是直接将图片用浏览器打开
console.log('dragover')
},false)
// _img_container.addEventListener('dragend',function(ev){
//  ev.stopPropagation();
//  ev.preventDefault();
//  console.log('dragend')
// },false)
_img_container.addEventListener('drop',function(ev){
//ev.stopPropagation();
ev.preventDefault();
console.log('drop')
//console.log(ev.dataTransfer.files[0])
reader.onload = function(ev){
//获取图片的url
var _img_src = ev.target.result;

//添加预览图片到容器框
showPrevImg(_img_container,_img_src);

}
reader.readAsDataURL(ev.dataTransfer.files[0])

},false)
}
//简化 document.getElementById() 函数
function getDomById(id){
return document.getElementById(id);
}
function showPrevImg(_img_container,_img_src){
_img_container.innerHTML="";
//添加预览图片到容器框
var _imgs = _img_container.getElementsByTagName('img');
//容器中没有则创建,有则修改 src 属性
if(!_imgs.lenght){
_imgs[0] = document.createElement('img');
_imgs[0].setAttribute('src',_img_src);
_img_container.appendChild(_imgs[0]);
}else{
_imgs[0].setAttribute('src',_img_src);
}
}
//接下来要做的就是拖放结束展示图片预览效果
</script>
</body>
</html>


展开完整代码
运行效果如下



四、结语

基本上实现以及代码的原理也就解释到这了。其实前端做的图片预览功能大多数需求是用来上传到服务器的。不得不提到的是这里的拖拽预览虽然看起来体验不错,但是要将该文件上传就得做一些特殊处理。这个我就留到后面的博客再讲了,有问题的朋友可以直接留言。

限于笔者技术,文章观点难免有不当之处,希望发现问题的朋友帮忙指正,笔者将会及时更新。也请转载的朋友注明文章出处并附上原文链接,以便读者能及时获取到文章更新后的内容,以免误导读者。笔者力求避免写些晦涩难懂的文章(虽然也有人说这样显得高逼格,专业),尽量使用简单的用词和例子来帮助理解。如果表达上有好的建议的话也希望朋友们在评论处指出。

本文为作者原创,转载请注明出处! Cboyce

html,div,span,applet,object,iframe,h2,h3,h4,h5,h6,p,blockquote,a,abbr,acronym,address,big,cite,code,del,dfn,em,img,ins,kbd,q,s,samp,small,strike,strong,sub,sup,tt,var,b,u,i,center,dl,dt,dd,ol,ul,li,fieldset,form,label,legend,article,aside,canvas,details,embed,figure,figcaption,footer,header,hgroup,menu,nav,output,ruby,section,summary,time,mark,audio,video { margin: 0; padding: 0; border: 0 }
body>*:first-child { margin-top: 0 !important }
body>*:last-child { margin-bottom: 0 !important }
p,blockquote,ul,ol,dl { margin: 15px 0 }
h2,h3,h4,h5,h6 { margin: 20px 0 10px; padding: 0; font-weight: bold }
h2 tt,h2 code,h3 tt,h3 code,h4 tt,h4 code,h5 tt,h5 code,h6 tt,h6 code { font-size: inherit }
h2 { font-size: 24px; border-bottom: 1px solid #ccc; color: #000 }
h3 { font-size: 18px }
h4 { font-size: 16px }
h5 { font-size: 14px }
h6 { color: #777; font-size: 14px }
a:first-child h2,a:first-child h3,a:first-child h4,a:first-child h5,a:first-child h6 { margin-top: 0; padding-top: 0 }
h2+p,h3+p,h4+p,h5+p,h6+p { margin-top: 10px }
a { color: #4183C4; text-decoration: none }
a:hover { text-decoration: underline }
ul,ol { padding-left: 30px }
ul li > :first-child, ol li > :first-child, ul li ul:first-of-type, ol li ol:first-of-type, ul li ol:first-of-type, ol li ul:first-of-type { margin-top: 0px }
ul ul,ul ol,ol ol,ol ul { margin-bottom: 0 }
dl { padding: 0 }
dl dt { font-size: 14px; font-weight: bold; font-style: italic; padding: 0; margin: 15px 0 5px }
dl dt:first-child { padding: 0 }
dl dt>:first-child { margin-top: 0px }
dl dt>:last-child { margin-bottom: 0px }
dl dd { margin: 0 0 15px; padding: 0 15px }
dl dd>:first-child { margin-top: 0px }
dl dd>:last-child { margin-bottom: 0px }
kbd { background-color: #DDDDDD; background-image: linear-gradient(#F1F1F1, #DDDDDD); background-repeat: repeat-x; border-color: #DDDDDD #CCCCCC #CCCCCC #DDDDDD; border-style: solid; border-width: 1px; font-family: "Helvetica Neue", Helvetica, Arial, sans-serif; line-height: 10px; padding: 1px 4px }
blockquote { border-left: 4px solid #DDD; padding: 0 15px; color: #777 }
blockquote>:first-child { margin-top: 0px }
blockquote>:last-child { margin-bottom: 0px }
hr { clear: both; margin: 15px 0; height: 0px; overflow: hidden; border: none; background: transparent; border-bottom: 4px solid #ddd; padding: 0 }
img { max-width: 100% }
.cj-img-container { text-align: center }
;
.cj-img-container img { max-width: 700px }
#cnblogs_post_body img { max-width: 700px }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: