Move And Limit Motion Of A Div Inside An Other Div
I have two simple divs, where one is contained inside an other div#numero{ position:absolute; background-color:#ff3324; border-style: solid; border-width: 2px;
Solution 1:
See http://jsfiddle.net/enHmy/
Add the following code after your html code
document.getElementById('cont').onmousemove=moveDiv;
And then your function should be:
functionmoveDiv(e){
if(!e){e=window.event;}
var el = document.getElementById('numero');
x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2;
y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2;
el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}
But let's analyse your function:
Why do you use document.all["numero"]
? That's very old and doesn't work on compliant browsers, now it's document.getElementById('numero');
.
And then you use window.event
. That works on IE, but you should pass an argument e
(the event) and, if e
is not defined (it's old IE), we set it to window.event
.
And when you are closing a CSS rule, don't write a semicolon after }
.
Edit:
If you scroll the page, numero
is not positioned correctly.
Fixed in http://jsfiddle.net/enHmy/1/:
functionmoveDiv(e){
if(!e){e=window.event;}
var el = document.getElementById('numero');
x = e.clientX-this.offsetLeft-this.clientLeft-el.offsetWidth/2+getScroll('Left');
y = e.clientY-this.offsetTop-this.clientTop-el.offsetHeight/2+getScroll('Top');
el.style.left = Math.min(Math.max(0,x),this.clientHeight-el.offsetWidth) +"px";
el.style.top = Math.min(Math.max(0,y),this.clientHeight-el.offsetHeight) +"px";
}
functiongetScroll(dir){
returnMath.max(document.body["scroll"+dir]||0,document.documentElement["scroll"+dir]||0);
}
Post a Comment for "Move And Limit Motion Of A Div Inside An Other Div"