将HTML5中的文件拖拽封装成了类,供需要的人使用:
drag.js:
document.write("<script language='javascript' src='utility.js'></script>");
//要放在哪个容器,容器的ID
function FileDrager(cntId){
this.containerId = cntId;
}
FileDrager.prototype = {
// 判断是否图片
isImage : function(type) {
switch (type) {
case 'image/jpeg':
case 'image/png':
case 'image/gif':
case 'image/bmp':
case 'image/jpg':
return true;
default:
return false;
}
},
初始化
Init : function(){
获得放图片的容器
var ctn = $(this.containerId);
ctn.addEventListener('dragover', function(evt) {
evt.stopPropagation();
evt.preventDefault();
}, false);
ctn.addEventListener('drop', function(e) {
e.stopPropagation();
e.preventDefault();
var fileList = e.dataTransfer.files, //获取拖拽文件
oImg = document.createElement('img'),
reader = new FileReader();
var c = ctn;
var x = e.clientX;
var y = e.clientY;
reader.onload = function(evt) {
oImg.src = this.result;
oImg.style.position = "absolute";
oImg.style.left = x;
= y;
c.appendChild(oImg);
}
reader.readAsDataURL(fileList[0]);
}, false);
}
}