<!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#div1{width: 100px;height:100px;background:red;position: absolute;}
</style>
<script type="text/javascript">
window.onload=function()
{
var oDiv=document.getElementById('div1');
var disX=0;//创建一个变量用来获取鼠标横向坐标
var disY=0
if(oDiv.setCapture)
oDiv.onmousedown=function(ev)//当鼠标按下时,获取鼠标位置
{
var oEvent=ev||event;
disX=oEvent.clientX-oDiv.offsetLeft;//鼠标位置等于可视区鼠标位置-需要移动的物体的offsetLeft
disY=oEvent.clientY-oDiv.offsetTop;
oDiv.onmousemove=function(ev){
var oEvent=ev||event;
var l=oEvent.clientX-disX;
var t=oEvent.clientY-disY;
if(l<0){l=0}
else if(l>document.documentElement.clientWidth-oDiv.offsetWidth)
{l=document.documentElement.clientWidth-oDiv.offsetWidth}
if(t<0){t=0}
else if(t>document.documentElement.clientHeight-oDiv.offsetHeight)
{t=document.documentElement.clientHeight-oDiv.offsetHeight}
oDiv.style.left=l+'px';
oDiv.style.top=t+'px'
}
oDiv.onmouseup=function()//当鼠标放开时,让函数取消
{
this.onmousemove=null;
this.onmouseup=null
oDiv.releaseCapture()
}
oDiv.setCapture();
}
else
{
oDiv.onmousedown=function(ev)//当鼠标按下时,获取鼠标位置
{
var oEvent=ev||event;
disX=oEvent.clientX-oDiv.offsetLeft;//鼠标位置等于可视区鼠标位置-需要移动的物体的offsetLeft
disY=oEvent.clientY-oDiv.offsetTop;
document.onmousemove=function(ev){
var oEvent=ev||event;
var l=oEvent.clientX-disX;
var t=oEvent.clientY-disY;
if(l<0){l=0}
else if(l>document.documentElement.clientWidth-oDiv.offsetWidth)
{l=document.documentElement.clientWidth-oDiv.offsetWidth}
if(t<0){t=0}
else if(t>document.documentElement.clientHeight-oDiv.offsetHeight)
{t=document.documentElement.clientHeight-oDiv.offsetHeight}
oDiv.style.left=l+'px';
oDiv.style.top=t+'px'
}
document.onmouseup=function()//当鼠标放开时,让函数取消
{
this.onmousemove=null;
this.onmouseup=null
oDiv.releaseCapture()
} return false
}
}
</script>
</head>
<body>
<div id='div1'>nininiinnn</div>
xnsuduwjndjkmmmmmmmmmmmmmm
xmisjdnusdjhhhhhhhhhhhhd<br>
</body>
</html>
stone310