。
<!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 http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Google</title>
<style type="text/css">
#div1{
overflow: hidden;
position: absolute;
top: 100px;
left:100px;
border:5px solid #000;
width:600px;
height:600px;
}
img{
border: 1px solid #000;
}
</style>
<script type="text/javascript">
var dragObject = null ;
var mouseOffset = null ;
document.onmousemove = mouseMove ;
document.onmouseup = mouseUp;
function mousePoint( x, y ){
this.x = x ;
this.y= y ;
}
function mousePosition( evnt ){
var x = parseInt( evnt.clientX );
var y = parseInt( evnt.clientY );
return new mousePoint(x,y);
}
function getMouseOffset( target , evnt ){
evnt = evnt || window.event ;
var mousePos = mousePosition(evnt);
var x = mousePos.x - target.offsetLeft;
var y = mousePos.y - target.offsetTop;
return new mousePoint(x,y);
}
//关闭拖拽
function mouseUp( evnt ){
dragObject = null ;
}
//拖拽时
function mouseMove( evnt ){
if( !dragObject ) return ;
evnt = evnt || window.event ;
var mousePos = mousePosition( evnt );
//
if( dragObject ){
dragObject.style.position = "absolute";
dragObject.style.top = mousePos.y - mouseOffset.y + "px";
dragObject.style.left = mousePos.x - mouseOffset.x + "px";
return false;
}
}
//
function makeDraggable( item ){
if( item ){
item = document.getElementById( item );
item.onmousedown = function( evnt ){
dragObject = this ;
mouseOffset = getMouseOffset( this , evnt );
return false ;
};
}
}
</script>
</head>
<body οnlοad="makeDraggable('img1');">
<div id="div1">
<img id="img1" src="test1.jpg"/>
</div>
</body>
</html>