Ciao, prova cosė:
Codice:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta name="keywords" content="" />
<meta name="description" content="" />
<meta http-equiv="imagetoolbar" content="no" />
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<meta http-equiv="revisit-after" content="7 days" />
<meta http-equiv="robots" content="index,follow" />
<meta http-equiv="Cache-Control" content="cache, must-revalidate" />
<meta http-equiv="pragma" content="cache" />
<link rel="stylesheet" type="text/css" href="css/stile.css" />
<title>Localhost</title>
<script type="text/javascript">
// inizializzazione variabili
var draggable = 0;
var mousex = 0;
var mousey = 0;
var elemX = 0;
var elemY = 0;
var dx = 0;
var dy = 0;
var X = 0;
var Y = 0;
var pippo=null;
var cords=null;
function init(){
pippo = document.getElementById('pippo');
cords = document.getElementById('cords');
document.onmousemove=function(event){drag(event);};
}
function calcola(evt) {
e = evt;
// posizione dell'elemento
elemX = parseInt(pippo.style.left);
elemY = parseInt(pippo.style.top);
// posizione del mouse sullo schermo
mousex = e.clientX;
mousey = e.clientY;
X = mousex + dx;
Y = mousey + dy;
}
// attiva il flag di trascinamento
function startDrag(evt) {
e=evt;
if(window.event) e=window.event;
draggable = 1;
dx = parseInt(pippo.style.left)-e.clientX;
dy = parseInt(pippo.style.top)-e.clientY;
}
// disattiva il flag di trascinamento
function stopDrag(evt) {
draggable = 0;
}
// trascinamento
function drag(evt) {
e=evt;
if(window.event) e=window.event;
//e = evt;
if (draggable == 1) {
calcola(e);
pippo.style.left = X + 'px';
pippo.style.top = Y + 'px';
cords.innerHTML = 'x=' + X;
cords.innerHTML += ' y=' + Y;
}
}
</script>
</head>
<body onload="init();">
<div id="pippo" onmousedown="startDrag(event)" onmouseup="stopDrag(event)" style="position:absolute; top:70px; left:50px; width:100px; height:70px; background:gray"></div>
<div id="cords" style="position:absolute; top:0px; right:0px"></div>
</body>
</html>