一、前言
最開始實現鼠標拖動元素的目的就是在一個頁面上拖動很多小圓點,用于固定定位,然后在復制HTML,粘貼在頁面的開發代碼中,就是這么一個功能,實現了很多遍,都沒有做好,不得已采用了jQuery.fn.draggable插件,在接觸一些資料和別人的思路,今天終于把這個拖動功能給完善了,下面就來看看它的實現
二、設計思路
在拖動元素上綁定鼠標按下事件,在文檔對象中綁定鼠標移動,鼠標彈起事件;
為什么不把三個事件都綁定在拖動元素上,這是因為鼠標移動太快時,鼠標移動和彈起事件處理程序將不會執行
$(document)
.bind('mousemove', fn)
.bind('mouseup', fn);
三、源碼實現細節
在實現源碼中有很多需要值得注意的地方:
1、首先在鼠標按下事件中,當單擊拖動元素中,可能會選擇區域文字,這并不是我們所需要的,解決方法如下:
2、如果拖動元素是圖片(img標簽),鼠標在拖動圖片一小段距離,會出現一個禁止的小提示,即:圖片不能再拖動,
這是瀏覽器的默認行為,因此只要阻止瀏覽器默認行為就可以了
3、關于邊界(處理拖動范圍)的問題
一開始實現的代碼如下:
if ( x >= limitObj._left && x <= limitObj._right ) {
$target.css({ left: x + 'px' });
}
if ( y >= limitObj._top && y <= limitObj._bottom ) {
$target.css({ top: y + 'px' });
}
進一步思考:為什么會出現上面問題,原因在于變量x可能會小于limitObj._left或大于limitObj._right,變量y同理,
因此代碼需要像下面這樣處理:
終于解決了這個問題,但是cloudgamer給出了更好的寫法:
完整程序源碼:
function _initOptions() {
var noop = function(){}, defaultOptions;
defaultOptions = { // 默認配置項
boundaryElem: 'body' // 邊界容器
};
options = $.extend( defaultOptions, options || {} );
$boundaryElem = $(options.boundaryElem);
dragStart = options.dragStart || noop,
dragMove = options.dragMove || noop,
dragEnd = options.dragEnd || noop;
}
function _drag(e) {
var clientX, clientY, offsetLeft, offsetTop,
$target = $(this), self = this;
limitObj = {
_left: 0,
_top: 0,
_right: ($boundaryElem.innerWidth() || $(window).width()) - $target.outerWidth(),
_bottom: ($boundaryElem.innerHeight() || $(window).height()) - $target.outerHeight()
};
// 記錄鼠標按下時的位置及拖動元素的相對位置
clientX = e.clientX;
clientY = e.clientY;
offsetLeft = this.offsetLeft;
offsetTop = this.offsetTop;
dragStart.apply(this, arguments);
$(document).bind('mousemove', moveHandle)
.bind('mouseup', upHandle);
// 鼠標移動事件處理
function moveHandle(e) {
var x = e.clientX - clientX + offsetLeft;
var y = e.clientY - clientY + offsetTop;
$target.css({
left: Math.max( Math.min(x, limitObj._right), limitObj._left) + 'px',
top: Math.max( Math.min(y, limitObj._bottom), limitObj._top) + 'px'
});
dragMove.apply(self, arguments);
// 阻止瀏覽器默認行為(鼠標在拖動圖片一小段距離,會出現一個禁止的小提示,即:圖片不能再拖動)
e.preventDefault();
}
// 鼠標彈起事件處理
function upHandle(e) {
$(document).unbind('mousemove', moveHandle);
dragEnd.apply(self, arguments);
}
}
_initOptions(); // 初始化配置對象
$(this)
.css({ position: 'absolute' })
.each(function(){
$(this).bind('mousedown', function(e){
_drag.apply(this, [e]);
// 阻止區域文字被選中 for chrome firefox ie9
e.preventDefault();
// for firefox ie9 || less than ie9
window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();
});
});
return this;
}
});
實例調用:
新聞熱點
疑難解答