I would like to perform a drag and drop on a div in HTML 5. The goal is to move a div anywhere in the mai开发者_如何学编程n container.
Here is my html code :
<html>
<head>
<title>Mon document</title>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="dragndrop.js"></script>
</head>
<body ondragstart="dragStart(event);" ondragover="return dragOver(event);" ondrop="return drop(event);">
<div class="box" draggable="true">
Drag me if you can !
</div>
</body>
The style.css :
.box {
position: absolute;
top: 100px;
left: 400px;
color: white;
background-color: #6495ED;
border: 10px solid #6495ED;
-webkit-box-shadow: 4px 4px 6px #999;
box-shadow: 4px 4px 12px #555;
border-radius: 7px;
width: 150px;
height: 150px;
}
body {
background-color:#EEEEEE;
}
And the javascript :
var mouseX; // Current mouse X coordinate
var mouseY; // Current mouse Y coordinate
document.onmousemove = mouseMove;
function dragStart(event) {
event.dataTransfer.effectAllowed = 'move';
event.dataTransfer.setData("Text", event.target.getAttribute('id'));
}
function dragOver(event) {
return false;
}
function drop(event) {
ev = event || window.event;
mouseX = ev.pageX;
mouseY = ev.pageY;
var element = event.dataTransfer.getData("Text");
document.getElementById(element).style.left = mouseX+"px";
document.getElementById(element).style.top = mouseY+"px";
event.stopPropagation();
return false;
}
It does not work, so I think there is something wrong in the javascript function drop. But I can not see what (I never worked with js before that).
Thanks for help.
I will follow this good advice and use jquery instead. I found here the demo and code I need : jQuery UI - draggable demo.
精彩评论