JS拖拽优化
拖拽的实现原理:通过事件mousedown(事件的触发) →mousemove(事件的控制) →mouseup(事件的清除),拖拽的过程就是mousemove阶段;
###问题产生的原因:因为mousemove 的间隔性触发,当两次mousemove事件触发的间隔中,鼠标移动距离出了element的范围,就会产生鼠标脱离element范围,拖拽就停止,
解决方法: 将mousemove事件挂在docment,而不是对应的element,此时鼠标滑动只要不出docment范围就不会触发上述情况。
JQuery拖拽优化
(function( $ ){
"use strict";
$.fn.drager = function( options ) {
//获取元素
//var dv = document.getElementById(options);
var x = 0;
var y = 0;
var l = 0;
var t = 0;
var isDown = false;
//鼠标按下事件
if(options){
var _left = options.left;
var _top = options.top;
$(this).css({left: _left * Global.common.screen_level + 'px'});
$(this).css({top: _top * Global.common.screen_level +'px'});
}
$(this).off('mousedown').on('mousedown',function(e) {
var _this = this
//获取x坐标和y坐标
x = e.clientX;
y = e.clientY;
//获取左部和顶部的偏移量
l = $(this).offset().left;
t = $(this).offset().top;
//开关打开
isDown = true;
//设置样式
$(this).css({cursor: 'pointer'});
$(document).mousemove(function(e){
if (isDown == false) {
return;
}
//获取x和y
var nx = e.clientX;
var ny = e.clientY;
//计算移动后的左偏移量和顶部的偏移量
var nl = nx - (x - l);
var nt = ny - (y - t);
$(_this).css({left: nl + 'px'});
$(_this).css({top: nt + 'px'});
})
$(document).mouseup(function(){
isDown = false;
$(this).css({cursor: 'default'});
})
})
}
})( jQuery );