(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.獲取層元素,在瀏覽器可視區域的最左、最邊,最上、最下的值。並且在拖動層的過程中,把當前層的坐標值,去和這幾個值,做比較,如果超過這些值。那么就不能再拖動這個方向,即把值設為最小或最大。
感覺我這些判斷有點復雜,有高手指點下,怎么簡化下嗎?
