在网页上拖放;
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
#div1 {width:300px;height:200px;padding:10px;background-color:#cccccc;}
</style>
<script>
function allowDrop(ev)
{
ev.preventDefault();
}
function drag(ev)
{
//得到拖拽数据 添加id 如“testImg”
ev.dataTransfer.setData("testImg",ev.target.id);
}
function drop(ev)
{
//调用 preventDefault() 来避免浏览器对数据的默认处理(drop 事件的默认行为是以链接形式打开)
ev.preventDefault();
var data=ev.dataTransfer.getData("testImg");
ev.target.appendChild(document.getElementById(data)); //把被拖元素追加到放置元素(目标元素)中
}
</script>
</head>
<body>
<p>拖动图片到灰色矩形中:</p>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br>
<img id="drag1" src="81.jpg" draggable="true" ondragstart="drag(event)">
</body>
</html>
2. 在本地拖放图片到网页上;
index3.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#imgcontainer{
margin: 0;
padding: 0;
width: 400px;
height: 400px;
background-color: #cccccc;
}
</style>
<script src="app3.js"></script>
</head>
<body>
<div id="imgcontainer">
</div>
<div id="showmsg"></div>
</body>
</html>
app3.js
var imgContainer,msgDiv;
window.onload = function(){
imgContainer = document.getElementById("imgcontainer");
msgDiv = document.getElementById("showmsg");
imgContainer.ondragover = function(e){
e.preventDefault();
}
imgContainer.ondrop = function(e){
e.preventDefault();
//得到要上传的图片数据
var f = e.dataTransfer.files[0];
var fileReader = new FileReader();
fileReader.onload = function(e){
//将其现实到指定区域
imgContainer.innerHTML = "<img src=\""+ fileReader.result+"\">"
}
fileReader.readAsDataURL(f);
}
}