现在的位置: 首页 > 综合 > 正文

jQuery 拖动层(在可视区域范围内)

2012年09月19日 ⁄ 综合 ⁄ 共 2204字 ⁄ 字号 评论关闭

复制代码 代码如下:
(function($){
$.fn.extend({
mydrag:function(){
var boxX = 0; //元素在页面中的横坐标
var boxY = 0; //元素在页面中的纵坐标
var dMouseX = 0; //按下鼠标时的鼠标所在位置的横坐标
var dMouseY = 0; //按下鼠标时的鼠标所在位置的纵坐标
var mMouseX = 0; //移动鼠标时的鼠标所在位置的横坐标
var mMouseY = 0; //移动鼠标时的鼠标所在位置的纵坐标
var moveLenX = 0; //存放鼠标移动的距离,横向
var moveLenY = 0; //存放鼠标移动的距离,纵向
var isMove = false; //是否拖动层的一个输助"开关"
var movingX = 0; //移动中元素的LEFT值
var movingY = 0; //移动中元素的TOP值
//可视区域最右边的值
var rightest = document.documentElement.clientWidth - $(".top").parent().outerWidth();
//可视区域最右边的值
var bottomest = document.documentElement.clientHeight - $(".top").parent().outerHeight();
//获得移动鼠标时的鼠标所在位置的坐标
var getMoveMouse = function(move){
mMouseX = move.pageX;
mMouseY = move.pageY;
}
//获得元素在页面中的当前的位置
var getbox = function(m){
boxX = $(".box").offset().left;
boxY = $(".box").offset().top;
}
//获得鼠标按下时的坐标
var getDownMouse = function(m){
dMouseX = m.pageX;
dMouseY = m.pageY;
}
//获得鼠标移动的距离值
var getMoveLen = function(){
moveLenX = mMouseX - dMouseX;
moveLenY = mMouseY - dMouseY;
}
//鼠标UP时,关闭移动,即鼠标移动也不会让元素移动;
$(document).mouseup(function(){
isMove = false;
})
//给元素的TOP绑定事件
$(this).
//按下时获得元素的坐标和当前鼠标的坐档;
mousedown(function(e){
getbox(e);
getDownMouse(e)
isMove = true;
}).
//移动时获得移动的距离,设置元素的TOP和LEFT值;
mousemove(function(e){
var $this = $(this);
getMoveMouse(e);
getMoveLen();
if(isMove){
//防止元素移出可视区域
//可视区域浏览器最左边
if(movingX<0){
$this.css({"left":0});
if(movingY<0){
$this.css({"top":0});
}else if(movingY > bottomest){
$this.css({"top":bottomest});
}else{
$this.css({"top":boxY+moveLenY});
}
}
//可视区域浏览器最上面
else if(movingY<0){
$this.css({"top":0});
if(movingX>rightest){
$this.css({"left":rightest});
}else{
$this.css({"left":boxX+moveLenX});
}
}
//可视区域浏览器最右边
else if(movingX > rightest){
$this.css({"left":rightest});
if(movingY > bottomest){
$this.css({"top":bottomest});
}else{
$this.css({"top":boxY+moveLenY});
}
}
//可视区域浏览器最下边
else if(movingY > bottomest){
$this.css({"top":bottomest});
if(movingX<0){
$this.css({"left":0});
}else{
$this.css({"left":boxX+moveLenX});
}
}
//其它情况,即在可视区域中间
else{
$this.css({"left":boxX+moveLenX,"top":boxY+moveLenY});
}
movingX = boxX+moveLenX;
movingY = boxY+moveLenY;
}
})
}
})
})(jQuery)

主要思路:
  1.鼠标移动多少距离,元素就同时移动多少距离,所以要获取到鼠标移动的距离;
  2.鼠标按下,并且移动,才拖动层。所以需要一个“开关”,在移动按下时打开,如果鼠标这里移动了,那么就移动层,如果这个“关闭”,那么鼠标移动时,层也不会一起移动。
  3.获取层元素,在浏览器可视区域的最左、最边,最上、最下的值。并且在拖动层的过程中,把当前层的坐标值,去和这几个值,做比较,如果超过这些值。那么就不能再拖动这个方向,即把值设为最小或最大。
感觉我这些判断有点复杂,有高手指点下,怎么简化下吗?

下载DEMO

抱歉!评论已关闭.