天天看點

JQUERY實作拖動層

剛出爐的 大家需要的拿去用吧

var DragAndDrop = function() {

var _clientWidth;

var _clientHeight;

var _controlObj;

var _dragObj;

var _flag = false;

var _dragObjCurrentLocation;

var _mouseLastLocation;

var getElementDocument = function(element) {

//傳回某元素的根元素

return element.ownerDocument || element.document

};

var dragMouseDownHandler = function(evt) {

if (_dragObj) {

evt = evt || window.event;

//擷取浏覽器寬

_clientWidth = document.body.clientWidth;

//擷取浏覽器高

_clientHeight = document.documentElement.scrollHeight;

_flag = true;

//定義結構體 儲存目前left和TOP的值

_dragObjCurrentLocation = {

x: $(_dragObj).offset().left,

y: $(_dragObj).offset().top

};

//定義結構體 儲存點選滑鼠時的位置坐标

_mouseLastLocation = {

x: evt.screenX,

y: evt.screenY

};

//綁定事件

$(document).bind("mousemove", dragMouseMoveHandler);

$(document).bind("mouseup", dragMouseUpHandler);

//組織預設動作

if (evt.preventDefault) {

evt.preventDefault()

} else {

evt.returnValue = false

}

}

};

var dragMouseMoveHandler = function(evt) {

if (_flag) {

evt = evt || window.event;

var _mouseCurrentLocation = {

x: evt.screenX,

y: evt.screenY

};

_dragObjCurrentLocation.x = _dragObjCurrentLocation.x + (_mouseCurrentLocation.x - _mouseLastLocation.x);

_dragObjCurrentLocation.y = _dragObjCurrentLocation.y + (_mouseCurrentLocation.y - _mouseLastLocation.y);

_mouseLastLocation = _mouseCurrentLocation;

$(_dragObj).css("left", _dragObjCurrentLocation.x + "px");

$(_dragObj).css("top", _dragObjCurrentLocation.y + "px");

//組織預設動作

if (evt.preventDefault) {

evt.preventDefault()

} else {

evt.returnValue = false

}

}

};

var dragMouseUpHandler = function(evt) {

if (_flag) {

evt = evt || window.event;

cleanMouseHandlers();

_flag = false

}

};

var cleanMouseHandlers = function() {

if (_controlObj) {

$(_controlObj.document).unbind("mousemove");

$(_controlObj.document).unbind("mouseup")

}

};

return {

//注冊事件

Register: function(dragObj, controlObj) {

_dragObj = dragObj;

_controlObj = controlObj;

$(_controlObj).bind("mousedown", dragMouseDownHandler)

}

}

} (); 

使用方法

<mce:style><!--

.div{width:200px; height:150px; border:1px solid #ccc; margin:10px;position:absolute}

.cursor{cursor:move}

--></mce:style><style mce_bogus="1">.div{width:200px; height:150px; border:1px solid #ccc; margin:10px;position:absolute}

.cursor{cursor:move}</style>

<body>

<div class="div" id="msg1">

<div class="cursor" id="title">DIV層二</div>

<div id="biger" style="top: 130px; position:absolute; border:1px solid #e7e7e7; width:100%; cursor:nw-resize">123</div>

</div>

<mce:script type="text/javascript"><!--

var title=document.getElementById('title');

var msg1=document.getElementById('msg1');

DragAndDrop.Register(msg1,biger)

// --></mce:script>

</body>