HTML5拖放资源
1、网页内拖放
代码示例:简单的拖动图片的示例
tuofang.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>拖放图片</title>
<style>
.box{
width:400px;
height:400px;
}
#box1{
background-color:aqua;
float: left;
}
#box2{
background-color: #cccccc;
float: left;
}
</style>
<script src="tuofang.js"></script>
</head>
<body>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
<img src="1.jpg" alt="美女" id="img1" style="width:300px;height:200px">
<div id="msg"></div>
</body>
</html>
tuofang.js文件:
var box1Div,box2Div,msgDiv,img1;
window.onload=function(){
box1Div=document.getElementById("box1");
box2Div=document.getElementById("box2");
msgDiv=document.getElementById("msg");
img1=document.getElementById("img1");
box1Div.ondragover=function(i){
i.preventDefault();
}
box2Div.ondragover=function(i){
i.preventDefault();
}
img1.ondragstart=function(i){
i.dataTransfer.setData("imgId","img1");
}
box1Div.ondrop=dropImghandler;
box2Div.ondrop=dropImghandler;
}
function dropImghandler(i){
showObj(i.dataTransfer);
i.preventDefault();
var img=document.getElementById(i.dataTransfer.getData("imgId"));
i.target.appendChild(img);
}
function showObj(obj){
var s="";
for(var k in obj){
s+=k+":"+obj[k]+"<br />"
}
msgDiv.innerHTML=s;
}
2、本地拖放到网页中
代码示例:
tuofang2.html文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>本地拖放</title>
<style>
#imgContainer{
background-color: #cccccc;
width: 500px;
height: 500px;
}
</style>
<script src="tuofang2.js"></script>
</head>
<body>
<div id="imgContainer"></div>
<div id="msg"></div>
</body>
</html>
tuofang2.js文件:
var imgContainer,msgDiv;
window.onload=function(){
imgContainer=document.getElementById("imgContainer");
msgDiv=document.getElementById("msg");
imgContainer.ondragover=function(i){
i.preventDefault();
}
imgContainer.ondrop=function(i){
i.preventDefault();
var f=i.dataTransfer.files[0];
var fileReader=new FileReader();
fileReader.onload=function(i){
showObj(i.target)
imgContainer.innerHTML="<img src=\""+fileReader.result+"\">"
}
fileReader.readAsDataURL(f);
}
}
function showObj(obj){
var s="";
for(var k in obj){
s+=k+":"+obj[k]+"<br />"
}
msgDiv.innerHTML=s;
} |
|