内容整理自网上!
一、拖放
实现效果:
拖放图片
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>播放视频</title>
<style>
.box{
width: 400px;
height: 400px;
}
#box1{
float: left;
background-color: #cccccc;
}
#box2{
float: left;
background-color: rosybrown;
}
</style>
</head>
<body>
<div id="box1" class="box"></div>
<div id="box2" class="box"></div>
![](resource/ok.jpg)
<div id="msg"></div>
<script>
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 (e) {
e.preventDefault();//阻止系统默认事件
}
box2Div.ondragover=function (e) {
e.preventDefault();//阻止系统默认事件
}
img1.ondragstart=function (e) {
e.dataTransfer.setData('imgId','img1');
}
box1Div.ondrop=dropImg;
box2Div.ondrop=dropImg;
}
function dropImg(e) {
// showObj(e.getDataTransfer);
e.preventDefault();
//创建结点
var img=document.getElementById(e.dataTransfer.getData('imgId'));
e.target.appendChild(img);
}
function showObj(obj) {
var s='';
for(var k in obj){
s+=k+':'+obj[k]+'<br/>';
}
msgDiv.innerHTML=s;
}
</script>
</body>
</html>
二、拖放本地资源
代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>播放视频</title>
<style>
#imgContainer{
background-color: rosybrown;
width: 300px;
height: 300px;
}
</style>
</head>
<body>
<div id="imgContainer"></div>
<script>
var imgContainer;
window.onload=function () {
imgContainer=document.getElementById('imgContainer');
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);
}
}
function showObj(obj) {
var s='';
for(var k in obj){
s+=k+':'+obj[k]+'<br/>';
}
msgDiv.innerHTML=s;
}
</script>
</body>
</html>
网友评论