sono riuscito a buttar giù del codice funzionante, permette di muovere il div a destra e a sinistra
posto il codice
Codice PHP:
<html>
<head>
<title>JavaScript muovi div</title>
<script language="javascript" type="text/javascript">
var animation = {
x: 0,
timer: undefined,
curX: 0,
millisec: 30,
moveRight: function(id){
var self = this;
var layerElement = document.getElementById(id);
self.x+=10;
layerElement.style.left=self.x;
var timer = setTimeout(function(){self.moveRight(id)},self.millisec);
self.timer = timer;
self.curX = self.x;
},
clearTimer: function(){
var self = this;
clearInterval(self.timer);
},
moveLeft: function(id){
var self = this;
var layerElement = document.getElementById(id);
self.x-=10;
layerElement.style.left=self.x;
var timer = setTimeout(function(){self.moveLeft(id)},self.millisec);
self.timer = timer;
self.curX = self.x;
}
}
</script>
</head>
<body>
<style type="text/css">
#cont{
position: relative;
width: 600px;
height: 400px;
background: #ccff00;
overflow: hidden;
}
#box{
position: absolute;
width: 100px;
height: 100px;
background: #ccc;
}
</style>
<div id="cont">
<div id="box">il mio box !</div>
</div>
<input type="BUTTON" value="left" onmousedown="animation.moveLeft('box')" onmouseup="animation.clearTimer()" />
<input type="BUTTON" value="right" onmousedown="animation.moveRight('box')" onmouseup="animation.clearTimer()" />
</body>
</html>
la proprietà animation.curX mi permette di rilevare l' attuale posizione del div, utile magari in uno script
secondo voi va bene, oppure si può migliorare il codice?