Доброго времени суток! Накидал предварительный скрипт, но он чего-то очень криво работает. JS изучаю недавно. Помогите разобраться плиз.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="charset=utf-8">
<style>
.thing {
width: 50px;
height: 50px;
border: 1px solid hsl(220, 10%, 30%);
background: hsl(220, 66%, 63%);
margin: 5px;
position: relative;
}
#cassa {
width: 100px;
height: 100px;
border: 1px solid hsl(220, 10%, 30%);
border-radius: 10px;
position: absolute;
top: 20px;
right: 20px;
}
</style>
</head>
<body id="clk">
<div class="thing"></div>
<div class="thing"></div>
<div class="thing"></div>
<div class="thing"></div>
<div id="cassa"></div>
<script>
window.addEventListener( "load", init(), false );
function init () {
var cassa = document.getElementById( "cassa" ), elem;
document.body.addEventListener( "mousedown", function (e) {
if ( e.target.getAttribute( "class" ) == "thing" ) {
elem = e.target; drag( e.target, e );
}
});
cassa.addEventListener( "mouseup", function (e) { drop( this, e, elem ); });
}
function drop ( box, event, elems ) {
if ( !elems ) return;
elems.style.top = elems.style.left = "0px";
box.appendChild( elems );
}
function drag ( elems, event ) {
var deltaX = event.clientX - elems.offsetLeft,
deltaY = event.clientY - elems.offsetTop;
document.addEventListener( "mousemove", moveHendler, true );
document.addEventListener( "mouseup", upHendler, true );
function moveHendler (e) {
if (!e) e = window.event;
elems.style.left = ( e.clientX - deltaX ) + "px";
elems.style.top = ( e.clientY - deltaY ) + "px";
}
function upHendler (e) {
if (!e) e = window.event;
document.removeEventListener( "mouseup", upHendler, true );
document.removeEventListener( "mousemove", moveHendler, true );
}
}
</script>
</body>
</html>
Спасибо!