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

2019-12-24,,

复制代码 代码如下:
(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

您可能感兴趣的文章:

  • js/jquery获取浏览器窗口可视区域高度和宽度以及滚动条高度实现代码
  • 使用jQuery判断Div是否在可视区域的方法 判断div是否可见
  • JQuery获取元素尺寸、位置及页面滚动事件应用示例
  • 基于jquery实现图片相关操作(重绘、获取尺寸、调整大小、缩放)
  • jquery中获得元素尺寸和坐标的方法整理
  • jQuery帮助之CSS尺寸(五)outerHeight、outerWidth
  • jQuery+CSS3实现仿花瓣网固定顶部位置带悬浮效果的导航菜单
  • 鼠标悬浮显示二级菜单效果的jquery实现
  • jQuery动画效果animate和scrollTop结合使用实例
  • 浅谈jQuery页面的滚动位置scrollTop、scrollLeft
  • JQuery获取可视区尺寸和文档尺寸及制作悬浮菜单示例

《jQuery 拖动层(在可视区域范围内).doc》

下载本文的Word格式文档,以方便收藏与打印。