简单的JQuery完美拖拽

首先导入jq库,最好是1.0版本的。调用函数时,传入要拖拽元素的id值。

function drag(sel){
$div = $("#"+sel);
$div.mousedown(function(evt){
var disX = evt.pageX-$(this).offset().left;
var disY = evt.pageY=$(this).offset().top;
$(document).mousemove(function(evt){
var left = evt.pageX-disX;
var top = evt.pageY-disY;
//设置left和top使其不超过边界
if(left<0){
left=0;
}else if(left>$(this).width()-$(sel).outerWidth(true)){
left=$(this).width()-$(sel).outerWidth(true);
}
if(top<0){
top=0;
}else if(top>$(this).height()-$(sel).outerHeight(true)){
top=$(this).height()-$(sel).outerHeight(true);
}
$div.css({"left":left,"top":top});
})
$(document).mouseup(function(){
$(this).off('mousemove');
})
})
}

猜你喜欢

转载自www.cnblogs.com/wyryuebanwan/p/9788210.html