<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>在网页中拖放文字</title>
<style>
body{
font-family: "微软雅黑";
}
div.drag{
background-color: #acf;
border:1px solid #666;
cursor:move;
cursor:pointer;
height:100px;
width:100px;
margin:10px;
float:left;
}
div.drop{
background-color: #eee;
border:1px solid #666;
cursor:pointer;
height:150px;
width:150px;
margin:10px;
float:left;
}
</style>
</head>
<body>
<div class="drag" draggable="true" οndragstart="dragstarthandler(event)">drag me!</div>
<div class="drop" οndragenter="dragenterhandler(event)" οndragοver="dragoverhandler(event)" οndrοp="drophandler(event)">drop here!</div>
<script>
function dragstarthandler(event){
event.dataTransfer.setData("Text",event.target.textContent);
event.effectAllowed="move";//允许拖放元素的哪种dropeffect,此处表示“move”
}
//dragenter事件
function dragenterhandler(event){
if(event.dataTransfer.types.contains("Text"))
if(event.preventDefault)
event.preventDefault();//规定在何处拖放被移动的数据
}
//dragover事件
function dragoverhandler(event){
event.dataTransfer.dropEffect="copy";
if(event.preventDefault)
event.preventDefault();//规定在何处拖放被移动的数据
}
//drop事件
function drophandler(event){
var data=event.dataTransfer.getData("Text");
var li=document.createElement("li");
li.textContent=data;
event.target.lastChild.appendChild(li);
}
</script>
</body>
</html>
<html>
<head>
<meta charset="UTF-8">
<title>在网页中拖放文字</title>
<style>
body{
font-family: "微软雅黑";
}
div.drag{
background-color: #acf;
border:1px solid #666;
cursor:move;
cursor:pointer;
height:100px;
width:100px;
margin:10px;
float:left;
}
div.drop{
background-color: #eee;
border:1px solid #666;
cursor:pointer;
height:150px;
width:150px;
margin:10px;
float:left;
}
</style>
</head>
<body>
<div class="drag" draggable="true" οndragstart="dragstarthandler(event)">drag me!</div>
<div class="drop" οndragenter="dragenterhandler(event)" οndragοver="dragoverhandler(event)" οndrοp="drophandler(event)">drop here!</div>
<script>
function dragstarthandler(event){
event.dataTransfer.setData("Text",event.target.textContent);
event.effectAllowed="move";//允许拖放元素的哪种dropeffect,此处表示“move”
}
//dragenter事件
function dragenterhandler(event){
if(event.dataTransfer.types.contains("Text"))
if(event.preventDefault)
event.preventDefault();//规定在何处拖放被移动的数据
}
//dragover事件
function dragoverhandler(event){
event.dataTransfer.dropEffect="copy";
if(event.preventDefault)
event.preventDefault();//规定在何处拖放被移动的数据
}
//drop事件
function drophandler(event){
var data=event.dataTransfer.getData("Text");
var li=document.createElement("li");
li.textContent=data;
event.target.lastChild.appendChild(li);
}
</script>
</body>
</html>