asked on
---[ HTML START]----------------8<----------------8<----------------8<----------------
<html>
<head>
<title></title>
<script type="text/javascript" src="drag.js"></script>
<style type="text/css">
.box {
width:500px;
height:650px;
background-color:#DDD;
}
.movable {
position: absolute;
width: 100px;
height: 100px;
background-color: yellow;
cursor:pointer;
border:solid 1px gray;}
</style>
</head>
<body>
<div class="box">
<div class="movable" style="left:100px; top:100px; position: absolute;" onmousedown="drag_start(this,event)"></div>
</div>
</body>
</html>
---[ HTML END]----------------8<----------------8<----------------8<--------------------
---[ JAVASCRIPT START]----------------8<----------------8<----------------8<-------
var posx;
var posy;
var zMax = 0;
var obj;
function drag_start(itemToMove, e,limit)
{
itemToMove.style.zIndex = ++window.zMax;
if (!e) e = window.event;
obj = itemToMove;
posx = e.clientX - parseInt(obj.style.left);
posy = e.clientY - parseInt(obj.style.top);
itemToMove.style.cursor="move";
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
function drag_stop(e)
{
if (obj) {
obj.style.cursor="pointer";
obj = null;
}
}
function drag(e)
{
if (!obj) return;
if (!e) e = window.event;
var height, width;
if (document.all)
{
height = document.body.offsetHeight;
width = document.body.offsetWidth;
}
else if (document.layers)
{
height = window.innerHeight;
width = window.innerWidth;
}
var newX = e.clientX - posx;
var newY = e.clientY - posy;
if (newX < -obj.clientWidth / 2)
{
newX = -obj.clientWidth / 2;
posx = e.clientX - parseInt(obj.style.left);
}
if (newY < -obj.clientHeight / 2)
{
newY = -obj.clientHeight / 2;
posy = e.clientY - parseInt(obj.style.top);
}
obj.style.left = newX;
obj.style.top = newY;
if (e.preventDefault) e.preventDefault();
else e.returnValue = false;
}
document.onmousemove = drag;
document.onmouseup = drag_stop;
document.ondragstart = function()
{
return false;
}
document.onselectstart = function()
{
return false;
}
---[ JAVASCRIPT END]----------------8<----------------8<----------------8<-----------