DIV CSS 佈局教程網

打造不超出可視範圍的 jQuery 拖曳浮層
編輯:JQuery特效代碼     

拖曳浮層是常見的互動效果,但若不加以限制,元素很容易就被拖出畫面。以下把這個功能封裝成 jQuery 外掛,並加入邊界判斷,確保浮層永遠留在瀏覽器可視範圍內。

. 代碼如下:

(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;
}
$(document).mouseup(function(){
isMove = false;
})
$(this).
mousedown(function(e){
getbox(e);
getDownMouse(e)
isMove = true;
}).
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. 取得浮層在瀏覽器可視區域的最左、最右、最上、最下界線,拖動過程中拿當前座標與這些界線比對,一旦超出就把值設為最小或最大,避免跑出畫面。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved