您的位置:首页 > Web前端 > JavaScript

简单实现的js拖动效果

2013-12-12 10:36 639 查看
<!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>
<title>拖拽</title>
<style>
html,body{height:100%;overflow:hidden;}
body,div,h2{margin:0;padding:0;}
body{font:12px/1.5 Tahoma;}
#win{position:absolute;top:40%;left:33%;width:400px;height:33px;background:#fc0;cursor:move;}
#win1{position:absolute;top:59%;left:59%;width:400px;height:33px;background:#fc0;cursor:move;}

</style>
<script>
window.onload = function ()
{
var oWin = document.getElementById("win");
var bDrag = false;
var disX = disY = 0;
oWin.onmousedown = function (e){
bDrag = true;
e= e||window.event;
disX = e.clientX - oWin.offsetLeft;
disY = e.clientY - oWin.offsetTop;
return false
};
document.onmousemove = function (e){
if (!bDrag)
return;
e= e||window.event;
var iL = e.clientX - disX;
var iT = e.clientY - disY;

//把图层范围定在浏览器窗口内
var maxL = document.documentElement.clientWidth - oWin.offsetWidth;
var maxT = document.documentElement.clientHeight - oWin.offsetHeight;
iL = iL < 0 ? 0 : iL;
iL = iL > maxL ? maxL : iL;
iT = iT < 0 ? 0 : iT;
iT = iT > maxT ? maxT : iT;

oWin.style.marginTop = oWin.style.marginLeft = 0;
oWin.style.left = iL + "px";
oWin.style.top = iT + "px";
return false
};
document.onmouseup = function (){
bDrag = false;
};
};
</script>
</head>
<body>
<div id="win">0</div>
</body>
</html>


大家请测试下.有bug的话.请大神指出下.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: