我已经开始学习JavaScript了。我尝试了以下操作将图像拖放到名为“dropTarget1”的dropzone中;图像不可拖动。你能不能看看我的代码,并告诉我我做错了什么。
var draggable=document.getElementById('dragMe1');
draggable.addEventListener('dragstart',dragStart,false);
var droptarget=document.getElementById("dropTarget1");
droptarget.addEventListener('dragenter',dragEnter,false);
droptarget.addEventListener('dragover',dragOver,false);
droptarget.addEventListener('dragleave',dragLeave,false);
droptarget.addEventListener('drop',drop,false);
function dragStart(event){
event.dataTransfer.setData('text/html', event.currentTarget.id);
}
function dragOver(event) {
event.preventDefault();
return false;
}
function drop(event) {
var dragMe1=document.createElement("img");
var data = event.dataTransfer.getData('text/html');
event.preventDefault();
event.stopPropagation();
dragMe1.src=data;
droptarget.appendChild('dragMe1');
return false;
}
#dropTarget1{
width:300px;
height:300px;
background-color:#DBF272;
}
#dragMe1{
width:300px;
}
#dragMe1 img{
padding-left:45px;
}
<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Untitled Document</title>
<link href="myStyle.css" rel="stylesheet" type="text/css">
</head>
<body>
<div id="dropTarget1"></div>
<img id="dragMe1" src="logo1.png" draggable="true" >
<script src="myDragnDrop.js"> </script>
</body>
</html>
答案 0 :(得分:0)
您的JavaScript代码应该是这样的(评论中的说明);
var draggable=document.getElementById('dragMe1');
var droptarget=document.getElementById("dropTarget1");
var newIm = document.createElement("img"); //Create new image element
/*Subscribe to dragover event.
This event fires when a user drag the image over the target */
droptarget.addEventListener('dragover',dragOver,false);
/*Subscribe to drop event.
This event fires when a user drop the image on the target */
droptarget.addEventListener('drop',drop,false);
function dragOver(event) {
event.stopPropagation(); //Prevent further drop events from bubbling up the DOM tree
event.preventDefault(); //Prevent the default behavior of the browser when dropping something on it
event.dataTransfer.dropEffect = "move"; //Specify the feedback that the user receives when a user drags over the target. It can be copy, link, or none
return false;
}
function drop(event) {
var data = event.dataTransfer.getData('text/plain'); //To retrieve the image URL
event.preventDefault();
event.stopPropagation();
newIm.src=data; //Write the image URL into the src attribute of newIm
droptarget.appendChild(newIm); //Add the new created image to the target element
document.body.removeChild(draggable); //Remove the original image as you're dragging and dropping (moving)
return false;
}
您不必订阅dragenter等活动,只需订阅dragover和drop事件即可。
答案 1 :(得分:0)
如果你想使用jQuery,那么这个Draggable|jquery UI可以是一个非常简单的选项。