DIV CSS 佈局教程網

動手寫一個 jQuery 拖曳插件:原理、步驟與完整實作
編輯:JQuery特效代碼     

拖曳效果在自訂彈窗、浮動工具列等介面中很常見。做之前先把原理釐清,寫起來就順了。

拖曳到底是什麼

顧名思義就是把元素拖來拖去,放到 DOM 上講,本質就是不斷改變它的位置。看似只有兩個難點:怎麼知道正在拖?怎麼知道從哪拖、拖到哪?但這兩件事其實都是基礎 API,關鍵在熟練。

四個步驟

1、讓元素捕獲事件,通常就是 mousedown、mousemove、mouseup。

2、在 mousedown 時標記開始拖曳,並記錄元素與滑鼠的位置。

3、在 mousemove 時持續取得滑鼠新位置,透過位置計算重新定位元素。

4、在 mouseup 時結束拖曳,然後周而復始。

要特別注意的一點:被拖曳的元素至少需要相對或絕對定位,否則拖曳不會有效果。

完整程式碼

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<title>Jeremy - DragDrop Test !</title>
<script type="text/javascript" src="jquery-1.4.2.min.js"></script>
<script type="text/javascript">
(function($) {
$.extend({
//獲取鼠標當前坐標
mouseCoords:function(ev){
if(ev.pageX || ev.pageY){
return {x:ev.pageX, y:ev.pageY};
}
return {
x:ev.clientX + document.body.scrollLeft - document.body.clientLeft,
y:ev.clientY + document.body.scrollTop - document.body.clientTop
};
},
//獲取樣式值
getStyle:function(obj,styleName)
{
return obj.currentStyle ? obj.currentStyle[styleName] : document.defaultView.getComputedStyle(obj,null)[styleName];
}
});
// 元素拖拽插件
$.fn.dragDrop = function(options)
{
var opts = $.extend({},$.fn.dragDrop.defaults,options);
return this.each(function(){
//是否正在拖動
var bDraging = false;
//移動的元素
var moveEle = $(this);
//點擊哪個元素以觸發移動,該元素需要是被移動元素的子元素(比如標題)
var focuEle = opts.focuEle ? $(opts.focuEle,moveEle) : moveEle ;
if(!focuEle || focuEle.length<=0)
{
alert('focuEle is not found! the element must be a child of '+this.id);
return false;
}
// initDiffX|Y : 初始時,鼠標與被移動元素原點的距離
// moveX|Y : 移動時,被移動元素定位位置(新鼠標位置與 initDiffX|Y 的差值)
// 如果定義了移動中的回調函數,該對象將以參數傳入回調函數
var dragParams = {initDiffX:'',initDiffY:'',moveX:'',moveY:''};
//被移動元素需要設置定位樣式,否則拖拽效果將無效
moveEle.css({'position':'absolute','left':'0','top':'0'});
//點擊時記錄鼠標位置
focuEle.bind('mousedown',function(e){
//標記開始移動
bDraging = true;
//改變鼠標形狀
moveEle.css({'cursor':'move'});
//捕獲事件(還有個好處:防止移動太快導致鼠標跑出被移動元素之外)
if(moveEle.get(0).setCapture)
{
moveEle.get(0).setCapture();
}
//實際上是鼠標當前位置相對於被移動元素原點的距離
dragParams.initDiffX = $.mouseCoords(e).x - moveEle.position().left;
dragParams.initDiffY = $.mouseCoords(e).y - moveEle.position().top;
});
//移動過程
focuEle.bind('mousemove',function(e){
if(bDraging)
{
//被移動元素的新位置,實際上是鼠標當前位置與原位置之差
dragParams.moveX = $.mouseCoords(e).x - dragParams.initDiffX;
dragParams.moveY = $.mouseCoords(e).y - dragParams.initDiffY;
//是否限定在某個區域中移動
//fixarea 格式: [x軸最小值,x軸最大值,y軸最小值,y軸最大值]
if(opts.fixarea)
{
if(dragParams.moveX<opts.fixarea[0])
{
dragParams.moveX=opts.fixarea[0]
}
if(dragParams.moveX>opts.fixarea[1])
{
dragParams.moveX=opts.fixarea[1]
}
if(dragParams.moveY<opts.fixarea[2])
{
dragParams.moveY=opts.fixarea[2]
}
if(dragParams.moveY>opts.fixarea[3])
{
dragParams.moveY=opts.fixarea[3]
}
}
//移動方向:可以是不限定、垂直、水平
if(opts.dragDirection=='all')
{
moveEle.css({'left':dragParams.moveX,'top':dragParams.moveY});
}
else if (opts.dragDirection=='vertical')
{
moveEle.css({'top':dragParams.moveY});
}
else if(opts.dragDirection=='horizontal')
{
moveEle.css({'left':dragParams.moveX});
}
//如果有回調
if(opts.callback)
{
//將 dragParams 作為參數傳遞
opts.callback.call(opts.callback,dragParams);
}
}
});
//鼠標彈起時,標記為取消移動
focuEle.bind('mouseup',function(e){
bDraging=false;
moveEle.css({'cursor':'default'});
if(moveEle.get(0).releaseCapture)
{
moveEle.get(0).releaseCapture();
}
});
});
};
//默認配置
$.fn.dragDrop.defaults =
{
focuEle:null, //點擊哪個元素開始拖動,可為空。不為空時需為被拖動元素的子元素
callback:null, //拖動時觸發的回調
dragDirection:'all', //拖動方向:['all','vertical','horizontal']
fixarea:null //限制在哪個區域拖動,以數組形式提供 [minX,maxX,minY,maxY]
};
})(jQuery);
// test
$(function(){
//限定區域,有回調函數
$('#dragDiv').dragDrop({fixarea:[0,$('#dragContainer').width()-50,0,$('#dragContainer').height()-50],callback:function(params){
$('#span1').text('X:'+params.moveX+' Y:'+params.moveY);
}});
//默認設置
$('#dragDiv1').dragDrop();
});
</script>
</head>
<body>
<div id="dragContainer" style="position:relative;left:10px;top:10px;border:1px dashed blue;width:500px;height:500px;">
<div id="dragDiv" style="background-color:blue;height:50px;width:50px;">
</div>
<div id="dragDiv1" style="border:1px solid red;height:50px;width:50px;">
</div>
</div>
<span id="span1"></span>
</body>
</html>

幾個設計上的巧思:initDiffX/Y 記錄滑鼠與元素原點的初始距離,讓元素在拖動時不會突然跳到滑鼠中心,手感更自然;setCapture() 進行滑鼠捕獲,避免移動過快時游標跑出元素範圍導致 mousemove 中斷;fixarea 則把可拖動範圍鎖在容器內。這些細節加起來,就是「能用」和「好用」的差距。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved