日期:2014-05-16  浏览次数:20418 次

【Javascript】求Div拖动代码,兼容FF以及子、父窗口div
如题
求js代码
能实现
按div顶部移动栏
可拖动本页面的div
以及当div处于子窗口或者父窗口的时候
也能拖动
最好兼容Firefox

------------
各位大侠请指教

------解决方案--------------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN " "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd ">
<html xmlns= "http://www.w3.org/1999/xhtml ">
<head>
<meta http-equiv= "Content-Type " content= "text/html; charset=gb2312 " />
<title> Drag类 </title>
<style type= "text/css ">
body {
margin:0px;
height:100%;
}
#wc_title {
width:100px;
height:20px;
background-color:#DCE2F1;
margin-bottom:5px;
cursor:move;
}
#wc {
z-index:100;
position:absolute;
width:100px;
height:60px;
background:#F0F8FF;
border:#CCCCCC 1px solid;
text-align:center;
font-size:12px;
}
</style>
<script type= "text/javascript ">
var Class = {
create: function () {
return function () {
this.initialize.apply(this, arguments);
};
}
};

var $A = Array.from = function(a) {
return a ? Array.apply(null, a) : new Array;
};

var $ = function (id) {
return document.getElementById(id);
}

Function.prototype.bind = function () {
var me = this, a = $A(arguments), o = a.shift();
return function() {
return me.apply(o, a.concat($A(arguments)));
}
}

var move = Class.create();

move.prototype = {

initialize : function () {
//初始化参数
var me = this, a = arguments;
me.obj = a[1] || a[0];
me.old_x = 0;
me.old_y = 0;
a[0].onmousedown = me.startDrag.bind(me);
},

rePosition : function (a) {
//返回位置
return a ? (document.body.offsetLeft == 0 ? document.documentElement.offsetLeft : document.body.offsetLeft) :
(document.body.offsetTop == 0 ? document.documentElement.offsetTop : document.body.offsetTop);
},

reEvent : function () {
//返回Event对象
return window.event || this.reEvent.caller.caller.arguments[0];
},

startDrag : function () {
//当按下时初始化参数
var me = this, e = me.reEvent();
me.old_x = me.rePosition(1) + e.clientX - me.obj.offsetLeft;
me.old_y = me.rePosition(0) + e.clientY - me.obj.offsetTop;
document.onmousemove = me.moveDrag.bind(me);
document.onmouseup = me.stopDrag;
},

moveDrag : function () {
//鼠标移动时改变obj的位置
var me = this, e = me.reEvent();
with (me.obj.style) {
left = e.clientX - me.old_x + "px ";
top = e.clientY - me.old_y + "px ";
}
},

stopDrag : function () {
//当松开时清除onmousemove方法
document.onmousemove = document.onmouseup = null;
}
};

window.onload = function () {
var wc = new move($( "wc_title "), $( "wc "));
};
</script>
</head>
<body>
<div id= "wc "> <div id= "wc_title "> &nbsp; <!--郁闷,必须要有内容否则FF拖不出浏览器--> </div> 传说中的Drag </div>
</body>
</html>