<pre name="code" class="html"><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>drag</title>
<meta name="author" content="Administrator" />
<!-- Date: 2014-07-19 -->
</head>
<style>
*{margin:0px;padding:0px;}
#div1{width:100px;height:100px;background:red;position:absolute;}
#div2{width:600px;height:600px;background:#555555;position:relative;}
</style>
<script>
window.οnlοad=function ()
{
var oDiv=document.getElementById("div1");
var oDiv2=document.getElementById("div2");
var disX=0;
var disY=0;
oDiv.οnmοusedοwn=function (ev)
{
var oEvent=ev || event;
disX=oEvent.clientX-oDiv.offsetLeft;
disY=oEvent.clientY-oDiv.offsetTop;
document.οnmοusemοve=function (ev)
{
var oEvent=ev || event;
var x=oEvent.clientX-disX;
var y=oEvent.clientY-disX;
if(x<50)//磁性吸附
{
x=0;
}else if(x>oDiv2.offsetWidth-oDiv.offsetWidth||oDiv2.offsetWidth-oDiv.offsetWidth-x<50)//指定跟随父级
{
x=oDiv2.offsetWidth-oDiv.offsetWidth;
}
if(y<50)
{
y=0;
}else if(y>oDiv2.offsetHeight-oDiv.offsetHeight||oDiv2.offsetHeight-oDiv.offsetHeight-y<50)
{
y=oDiv2.offsetHeight-oDiv.offsetHeight;
}//阻止超出可视区
oDiv.style.left=x+'px';
oDiv.style.top=y+'px';
};
document.οnmοuseup=function ()
{
document.οnmοusemοve=null;
document.οnmοuseup=null;
};
return false;//阻止ff默认行为;解决ffbug;
};
};
</script>
<body>
<div id="div2">
<div id="div1"></div>
</div>
</body>
</html>
js原生拖拽
最新推荐文章于 2024-09-03 09:43:43 发布