1、图片的拖放
效果图:
html代码
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>drag drog</title>
<style type="text/css">
#box1{
float: left;
width: 300px;
height: 300px;
background: gray;
}
#box2{
float: left;
width: 300px;
height: 300px;
background: red;
}
img{
width: 100px;
}
</style>
<script type="text/javascript" src="js/drag.js" ></script>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<img id="img1" src="img/0.jpg"/>
</body>
</html>
js代码
var boxDiv,boxDiv2,img;
window.onload = function(){
boxDiv = document.getElementById("box1");
boxDiv2 = document.getElementById("box2");
img = document.getElementById("img1");
boxDiv.ondragover = function(e){
//阻止默认的事件
e.preventDefault();
}
boxDiv2.ondragover = function(e){
//阻止默认的事件
e.preventDefault();
}
img.ondragstart = function(e){
//获取拖放的图片的数据
e.dataTransfer.setData("timg","img1");
}
boxDiv.ondrop = function(e){
e.preventDefault();
var timg = document.getElementById(e.dataTransfer.getData("timg"));
//当图片拖放在此区域时,将图片添加在此区域
e.target.appendChild(timg);
}
boxDiv2.ondrop = function(e){
e.preventDefault();
var timg = document.getElementById(e.dataTransfer.getData("timg"));
e.target.appendChild(timg);
}
}
2、本地图片拖放
效果:
html代码:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#box{
width: 400px;
height: 400px;
background: gray;
}
img{
width: 100px;
height: 100px;
}
</style>
<script type="text/javascript" src="js/location.js" ></script>
</head>
<body>
<div id="box"></div>
</body>
</html>
js代码:
var box;
window.onload = function(){
box = document.getElementById("box");
msg= document.getElementById("msg");
box.ondragover = function(e){
e.preventDefault();
}
box.ondrop = function(e){
e.preventDefault();
// showData(e.dataTransfer);
var f = e.dataTransfer.files[0];
var fileReader = new FileReader();
fileReader.readAsDataURL(f);
fileReader.onload = function(e){
// showData(e.target);
box.innerHTML = "<img src=\""+fileReader.result + "\"/>"
}
}
}
//function showData(obj){
// var s = "";
// for(var k in obj){
// s += k + ":" + obj[k] + "<br/>";
///}
//msg.innerHTML = s;
//}