前端开发经常需要将弹窗设置为可鼠标拖曳,单个弹窗问题不大,如果是多个弹窗,存在相互干扰的情况,笔者设计了一种方案,将窗口id存到数组中,弹出和关闭采用入栈和出栈方式,先看代码:
var _width_0, _height_0;
var _title_height = 40;
var _window_minWH = 100;
var a_window_id = [];
function set_drag(dragid) {
var odivid = "#" + dragid;
_width_0 = parseInt($(odivid).css("width"));
_height_0 = parseInt($(odivid).css("height"));
$(function () {
var _move = false;
var _to_rightborder = false, _to_bottomborder = false;
var _x, _y;
var _x_max, _y_max;
var _width, _height;
var x, y;
var _top, _left;
var expand = 2;
$(odivid).click(function () {
}).mousedown(function (e) {
var _x_left = parseInt($(odivid).css("left"));
var _y_top = parseInt($(odivid).css("top"))
_x = e.pageX - _x_left;
_y = e.pageY - _y_top;
_x_max = $(window).width() - _x_left - expand;
_y_max = $(window).height() - _y_top - expand;
if (e.pageY - _y_top <= _title_height && _x >= _window_minWH) {
_move = true;
_top = _y; _left = _x;
_to_rightborder = false;
_to_bottomborder = false;
}
else {
_move = false;
if (_x <= _width + expand && _x >= _width - expand) {
_to_rightborder = true;
}
if (_y <= _height + expand && _y >= _height - expand) {
_to_bottomborder = true;
}
}
});
$(document).mousemove(function (e) {
_width = parseInt($(odivid).css("width"));
_height = parseInt($(odivid).css("height"));
_x = e.pageX - parseInt($(odivid).css("left"));
_y = e.pageY - parseInt($(odivid).css("top"));
if (_move) {
x = e.pageX - _left;
y = e.pageY - _top;
}
//光标处理
var a_cursor = ["default", "move", "e-resize", "s-resize", "se-resize"];
var n_cursor = 0;
var n_cursor_e = 0;
var n_cursor_s = 0;
if (_y <= _title_height)
n_cursor = 1;
else {
n_cursor_e = 0;
n_cursor_s = 0;
if (_x <= _width + expand && _x >= _width - expand)
n_cursor_e = 2;
if (_y <= _height + expand && _y >= _height - expand)
n_cursor_s = 3;
if (n_cursor_e * n_cursor_s > 0)
n_cursor = 4;
else
n_cursor = n_cursor_e + n_cursor_s;
}
$(odivid).css("cursor", a_cursor[n_cursor]);
if (_move) {
$(odivid).css({ top: y, left: x });
}
else {
if (_to_rightborder) {
if (_x < _x_max && _x > _window_minWH) {
$(odivid).css({ width: _x });
}
}
if (_to_bottomborder) {
if (_y < _y_max && _y > _window_minWH) {
$(odivid).css({ height: _y });
}
}
}
}).mouseup(function () {
_move = false;
_to_rightborder = false;
_to_bottomborder = false;
});
});
}
如果需要弹窗(id:testid)可拖曳,直接运行:
set_darg(testid);
注意:
var _title_height = 40; var _window_minWH = 100;
定义标题高度_title_height ,弹窗最小宽度和高度_window_minWH
在生成弹窗HTML时需要将id入栈:
if (a_window_id.length > 0) {
var nIndex = a_window_id.indexOf(div_id);
while (nIndex >= 0 && a_window_id.length > 0) {
a_window_id.splice(nIndex, 1);
nIndex = a_window_id.indexOf(div_id);
}
}
a_window_id.push(div_id);
关闭弹窗时需要出栈操作:
function drag_close(div_id) {
if (div_id != undefined)
$("#" + div_id).hide();
if (a_drag_id.length > 0) {
a_drag_id.pop();
if (a_drag_id.length > 0) {
var pre_drag_id = a_drag_id.pop();
a_drag_id.push(pre_drag_id);
try {
set_drag(pre_drag_id);//激活栈顶层窗口
} catch (e) { }
}
}
else a_drag_id.push(div_id);
}
|