转自:http://www.muzilei.com/archives/136
如何实现拖动效果?
首先分析下拖动效果原理:
1.当鼠标在被拖动对象上按下鼠标(触发onmousedown事件,且鼠标在对象上方)
2.开始移动鼠标(触发onmousemove事件)
3.移动时更显对象的top和left值
4.鼠标放开停止拖动(触发onmouseup事件)
注意:拖动的对象必须是定位对象(即设置了position:absolute或 relative)。
也就是说拖动事件=onmousedown事件+onmousemove事件
整个过程就是处理这三个事件来模拟drag事件
现在看看我实现的源代码:
html代码:
1 |
<div class="drag">
|
2 |
<p class="title">标题(点击标题拖动)</p>
|
3 |
</div>
|
4 |
5 |
<div class="drag1">
|
6 |
<p class="title">标题</p>
|
7 |
点击我移动
|
8 |
</div>
|
jquery插件代码:
1 |
(function($){
|
2 |
$.fn.drag=function(options){
|
3 |
4 |
//默认配置
|
5 |
var defaults = {
|
6 |
handler:false,
|
7 |
opacity:0.5
|
8 |
};
|
9 |
10 |
// 覆盖默认配置
|
11 |
var opts = $.extend(defaults, options);
|
12 |
13 |
this.each(function(){
|
14 |
15 |
//初始标记变量
|
16 |
var isMove=false,
|
17 |
//handler如果没有设置任何值,则默认为移动对象本身,否则为所设置的handler值
|
18 |
handler=opts.handler?$(this).find(opts.handler):$(this),
|
19 |
_this=$(this), //移动的对象
|
20 |
dx,dy;
|
21 |
22 |
$(document)
|
23 |
//移动鼠标,改变对象位置
|
24 |
.mousemove(function(event){
|
25 |
// console.log(isMove);
|
26 |
if(isMove){
|
27 |
28 |
//获得鼠标移动后位置
|
29 |
var eX=event.pageX,eY=event.pageY;
|
30 |
31 |
//更新对象坐标
|
32 |
_this.css({'left':eX-dx,'top':eY-dy});
|
33 |
34 |
}
|
35 |
})
|
36 |
37 |
//当放开鼠标,停止拖动
|
38 |
.mouseup(function(){
|
39 |
isMove=false;
|
40 |
_this.fadeTo('fast', 1);
|
41 |
//console.log(isMove);
|
42 |
});
|
43 |
44 |
handler
|
45 |
//当按下鼠标,设置标记变量isMouseDown为true
|
46 |
.mousedown(function(event){
|
47 |
48 |
//判断最后触发事件的对象是否是handler
|
49 |
if($(event.target).is(handler)){
|
50 |
51 |
isMove=true;
|
52 |
$(this).css('cursor','move');
|
53 |
54 |
//console.log(isMove);
|
55 |
_this.fadeTo('fast', opts.opacity);
|
56 |
57 |
//鼠标相对于移动对象的坐标
|
58 |
dx=event.pageX-parseInt(_this.css("left"));
|
59 |
dy=event.pageY-parseInt(_this.css("top"));
|
60 |
61 |
}
|
62 |
});
|
63 |
});
|
64 |
};
|
65 |
})(jQuery);
|
调用方法:
1 |
$(function(){
|
2 |
3 |
//拖动标题 |
4 |
$(".drag").drag({
|
5 |
handler:$('.title'),//操作拖动的对象,此对象必须是移动对象的子元素
|
6 |
opacity:0.7 //设置拖动时透明度
|
7 |
});
|
8 |
9 |
//拖动主体对象 |
10 |
$(".drag1").drag({
|
11 |
opacity:0.7
|
12 |
});
|
13 |
14 |
}); |