對于某區(qū)域的拖動功能主要用到mousedown,mousemove和mouseup事件痹籍,具體代碼如下:
function pauseEvent(e){
if(e.stopPropagation) e.stopPropagation();
if(e.preventDefault) e.preventDefault();
e.cancelBubble=true;
e.returnValue=false;
return false;
}
$('.selectMajor .co_tit').mousedown(function(ev){
var e = ev||event;
pauseEvent(e);
var mdX = e.clientX;
var mdY = e.clientY;
var ele_top = $('.selectMajor').position().top;
var ele_left = $('.selectMajor').position().left;
var ele_width = $('.selectMajor').width();
var ele_height = $('.selectMajor').height();
var win_width = $(window).width();
var win_height = $(window).height();
// IE8 取消默認行為-設(shè)置全局捕獲
if ($('.selectMajor .co_tit').setCapture) {
$('.selectMajor .co_tit').setCapture();
}
document.onmousemove = function(ev2) {
var e2 = ev2||event;
pauseEvent(e2);
var mmX = e2.clientX;
var mmY = e2.clientY;
var moveX = mmX-mdX;
var moveY = mmY-mdY;
var target_top = ((ele_top+moveY) > (win_height-ele_height)) ? (win_height-ele_height) : (ele_top+moveY)
target_top = target_top < 0 ? 0 : target_top
var target_left = (ele_left+moveX-400) < 0 ? 400 : ( (ele_left+moveX-400)>(win_width-ele_width) ? (win_width-ele_width+400) : ele_left+moveX )
$('.selectMajor').css('top',target_top+'px');
$('.selectMajor').css('left',target_left+'px');
}
})
document.onmouseup = function() {
document.onmousemove = null;
// 釋放全局捕獲
if ($('.selectMajor .co_tit').releaseCapture) {
$('.selectMajor .co_tit').releaseCapture();
}
}
在測試時會發(fā)現(xiàn)呢铆,如果不加pauseEvent方法時,會出現(xiàn)時常mouseup事件丟失的情況蹲缠。具體原因:
- 觸發(fā)了瀏覽器的 drag 操作棺克,導致mouseup丟失悠垛。
- 由于鼠標離開了操作的區(qū)域,觸發(fā)了mouseleave導致mouseup丟失逆航。
加的pauseEvent方法就是用來防止觸發(fā)drag操作的鼎文。