本文實(shí)例講述了jQuery實(shí)現(xiàn)簡(jiǎn)單的DIV拖動(dòng)效果。分享給大家供大家參考,具體如下:
創(chuàng)建一個(gè)HTML文件,復(fù)制以下代碼進(jìn)去,修改jquery文件(沒(méi)有的到網(wǎng)上去下一個(gè),我使用的是jquery-1.8.2),即可以運(yùn)行了
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=gb2312" /><title>Jquery:鼠標(biāo)拖動(dòng)DIV</title><style type="text/css"> div#computerMove{ position:absolute; top:50px; left:50px; width:200px; height:30px; line-height:30px; background-color:#00CCCC; text-align:center; color:#FFFFFF; cursor:default; }</style></head><body> <div id="computerMove">點(diǎn)擊我拖動(dòng)</div> <script src="jquery-1.8.2.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function(){ var $div = $("div#computerMove"); /* 綁定鼠標(biāo)左鍵按住事件 */ $div.bind("mousedown",function(event){ /* 獲取需要拖動(dòng)節(jié)點(diǎn)的坐標(biāo) */ var offset_x = $(this)[0].offsetLeft;//x坐標(biāo) var offset_y = $(this)[0].offsetTop;//y坐標(biāo) /* 獲取當(dāng)前鼠標(biāo)的坐標(biāo) */ var mouse_x = event.pageX; var mouse_y = event.pageY; /* 綁定拖動(dòng)事件 */ /* 由于拖動(dòng)時(shí),可能鼠標(biāo)會(huì)移出元素,所以應(yīng)該使用全局(document)元素 */ $(document).bind("mousemove",function(ev){ /* 計(jì)算鼠標(biāo)移動(dòng)了的位置 */ var _x = ev.pageX - mouse_x; var _y = ev.pageY - mouse_y; /* 設(shè)置移動(dòng)后的元素坐標(biāo) */ var now_x = (offset_x + _x ) + "px"; var now_y = (offset_y + _y ) + "px"; /* 改變目標(biāo)元素的位置 */ $div.css({ top:now_y, left:now_x }); }); }); /* 當(dāng)鼠標(biāo)左鍵松開,接觸事件綁定 */ $(document).bind("mouseup",function(){ $(this).unbind("mousemove"); }); }) </script></body></html>更多關(guān)于jQuery相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《jQuery拖拽特效與技巧總結(jié)》、《jQuery擴(kuò)展技巧總結(jié)》、《jQuery常見經(jīng)典特效匯總》及《jQuery動(dòng)畫與特效用法總結(jié)》
希望本文所述對(duì)大家jQuery程序設(shè)計(jì)有所幫助。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注