$(document).mousemove(
function
(e) {
if
(!!
this
.move) {
var
posix = !document.move_target ? {
'x'
: 0,
'y'
: 0} : document.move_target.posix,
callback = document.call_down ||
function
() {
$(
this
.move_target).css({
'top'
: e.pageY - posix.y,
'left'
: e.pageX - posix.x
});
};
callback.call(
this
, e, posix);
}
}).mouseup(
function
(e) {
if
(!!
this
.move) {
var
callback = document.call_up ||
function
(){};
callback.call(
this
, e);
$.extend(
this
, {
'move'
:
false
,
'move_target'
:
null
,
'call_down'
:
false
,
'call_up'
:
false
});
}
});
原理稍后分析,先來看看效果:
title="" width="800" height="219" border="0" hspace="0" vspace="0" style="width: 800px; height: 219px;"/>
將代碼剝離,只要寫5行就可以實現拖拽了,是不是很簡單:
1
2
3
4
5
6
|
$(
'#box'
).mousedown(
function
(e) {
var
offset = $(
this
).offset();
this
.posix = {
'x'
: e.pageX - offset.left,
'y'
: e.pageY - offset.top};
$.extend(document, {
'move'
:
true
,
'move_target'
:
this
});
});
|
將代碼剝離,原先的代碼保留不變,增加一個綁定事件:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
|
var
$box = $(
'#box'
).mousedown(
function
(e) {
var
offset = $(
this
).offset();
this
.posix = {
'x'
: e.pageX - offset.left,
'y'
: e.pageY - offset.top};
$.extend(document, {
'move'
:
true
,
'move_target'
:
this
});
}).on(
'mousedown'
,
'#coor'
,
function
(e) {
var
posix = {
'w'
: $box.width(),
'h'
: $box.height(),
'x'
: e.pageX,
'y'
: e.pageY
};
$.extend(document, {
'move'
:
true
,
'call_down'
:
function
(e) {
$box.css({
'width'
: Math.max(30, e.pageX - posix.x + posix.w),
'height'
: Math.max(30, e.pageY - posix.y + posix.h)
});
}});
return
false
;
});
|
這樣來實現放大、縮小、拖拽是不是很簡答,還能實現很多其他效果,大家慢慢領悟。
原理分析:
放大、縮小、拖拽都離不開在網頁上拖動鼠標,對於前端來說就是document的mousemove,當鼠標在網頁上移動的時候,無時無刻不在觸發mousemove事件,當鼠標觸發事件時,什么時候需要執行我們特定的操作,這就是我們要做的了。我在mousemove中增加了幾個對象來判定是否進行操作:
move:是否執行觸發操作
move_target:操作的元素對象
move_target.posix:操作對象的坐標
call_down:mousemove的時候的回調函數,傳回來的this指向document
call_up:當鼠標彈起的時候執行的回調函數,傳回來的this指向document
小提示:
簡單的操作,只需要設定move_target對象,設置move_target的時候不要忘記了move_target.posix哦;
復雜的操作可以通過call_down、call_up進行回調操作,這個時候是可以不用設置move_target對象的