jQuery 拖動層(在可視區域范圍內)
2024-05-06 14:21:50
供稿:網友
代碼如下:
(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});
}
}
//其它情況,即在可視區域中間