jQuery拖拽div實現思路_jquery

來源:互聯網
上載者:User
思路是利用jquery的mousemove,mousedown,mouseup三個事件,定義兩個相對位置,分別是

1、組件左上方與螢幕左上方的相對位置

2、滑鼠所在座標與組件左上方的相對位置。

具體函數如下:

複製代碼 代碼如下:

.drag{
position:absolute;
background:#0000CC;
top:100px;left:200px;
padding:0;
}

複製代碼 代碼如下:

$(document).ready(function(){
var move=false;//移動標記
var _x,_y;//滑鼠離控制項左上方的相對位置
$(".drag").mousedown(function(e){
move=true;
_x=e.pageX-parseInt($(".drag").css("left"));
_y=e.pageY-parseInt($(".drag").css("top"));
});
$(document).mousemove(function(e){
if(move){
var x=e.pageX-_x;//控制項左上方到螢幕左上方的相對位置
var y=e.pageY-_y;
$(".drag").css({"top":y,"left":x});
}
}).mouseup(function(){
move=false;
});

其中e.pageX,e.pageY為當前滑鼠的橫縱座標。

大家自己動手試一下,思路就更加清晰了~

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.