这里只需要注意一点,因为默认情况下,浏览器是禁止元素drop的,所以为了让元素可以drop,需要在这个函数中返回false或者调用event.preventDefault()方法。如下面的例子所示。
拖动结束-ondrop,ondragend事件
当可拖动的数据被drop的时候,drop事件触发。drop结束后,dragend事件被触发,这个事件使用的也相对少一点。
看一个简单的例子:
<!DOCTYPEHTML>
<html>
<head>
<scripttype="text/javascript">
functionallowDrop(ev){
ev.preventDefault();
}
functiondrag(ev){
ev.dataTransfer.setData("Text",ev.target.id);
}
functiondrop(ev){
vardata=ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(data));
ev.preventDefault();
}
</script>
</head>
<body>
<divid="div1"ondrop="drop(event)"ondragover="allowDrop(event)"></div>
<imgid="drag1"src="img_logo.gif"draggable="true"ondragstart="drag(event)"width="336"height="69"/>
</body>
</html>
文件拖拽
上面的例子已经使用了dataTransfer的各种方法和属性,下面再看网上的另外一个有趣的应用:拖拽一个图片到网页上,然后在网页上显示。这个应用用到了dataTransfer的files属性。
<!DOCTYPEHTML>
<html>
<head>
<metacharset="utf-8">
<title>HTML5拖放文件</title>
<style>
#section{font-family:"Georgia","微软雅黑","华文中宋";}
.container{display:inline-block;min-height:200px;min-width:360px;color:#f30;padding:30px;border:3pxsolid#ddd;-moz-border-radius:10px;-webkit-border-radius:10px;border-radius:10px;}
.preview{max-width:360px;}
#files-list{position:absolute;top:0;left:500px;}
#list{width:460px;}
#list.preview{max-width:250px;}
#listp{color:#888;font-size:12px;}
#list.green{color:#09c;}
</style>
</head>
<body>
<divid="section">
<p>把你的图片拖到下面的容器内:</p>
<divid="container"class="container">
</div>
<divid="files-list">
<p>已经拖进过来的文件:</p>
<ulid="list"></ul>
</div>
</div>
<script>
if(window.FileReader){
varlist=document.getElementById('list'),
cnt=document.getElementById('container');
//判断是否图片
functionisImage(type){
switch(type){
case'image/jpeg':
case'image/png':
case'image/gif':
case'image/bmp':
case'image/jpg':
returntrue;
default:
returnfalse;
}
}
//处理拖放文件列表
functionhandleFileSelect(evt){
evt.stopPropagation();
evt.preventDefault();
varfiles=evt.dataTransfer.files;
for(vari=0,f;f=files[i];i++){
vart=f.type?f.type:'n/a',
reader=newFileReader(),
looks=function(f,img){
list.innerHTML+='<li><strong>'+f.name+'</strong>('+t+
')-'+f.size+'bytes<p>'+img+'</p></li>';
cnt.innerHTML=img;
},
isImg=isImage(t),
img;
//处理得到的图片
if(isImg){
reader.onload=(function(theFile){
returnfunction(e){
img='<imgclass="preview"src="'+e.target.result+'"title="'+theFile.name+'"/>';
looks(theFile,img);
};
})(f)
reader.readAsDataURL(f);
}else{
img='"o((>ω<))o",你传进来的不是图片!!';
looks(f,img);
}
}
}
//处理插入拖出效果
functionhandleDragEnter(evt){this.setAttribute('style','border-style:dashed;');}
functionhandleDragLeave(evt){this.setAttribute('style','');}
//处理文件拖入事件,防止浏览器默认事件带来的重定向
functionhandleDragOver(evt){
evt.stopPropagation();
evt.preventDefault();
}
cnt.addEventListener('dragenter',handleDragEnter,false);
cnt.addEventListener('dragover',handleDragOver,false);
cnt.addEventListener('drop',handleFileSelect,false);
cnt.addEventListener('dragleave',handleDragLeave,false);
}else{
document.getElementById('section').innerHTML='你的浏览器不支持啊,同学';
}
</script>
</body>
</html>