HTML源代码
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>拖拽实例</title> <link rel="stylesheet" href="drag.css"> <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script> <script src="drag.js"></script> </head> <body> <div></div> </body> </html>
CSS源代码
*{ margin: 0; padding:0; } div{ width: 100px; height: 100px; background: #f00; cursor: pointer; position: absolute; left: 0; top: 0; }
JS源代码
$(function(){ $('div').mousedown(function(e){ //offset()在匹配的元素集合中,获取的第一个元素的当前坐标,坐标相对于文档 var positionDiv = $(this).offset(); var distenceX = e.pageX - positionDiv.left; var distenceY = e.pageY - positionDiv.top; // alert(positionDiv.left); $(document).mousemove(function(e) { var x = e.pageX - distenceX; var y = e.pageY - distenceY; //防止将元素拖拽出浏览器窗口 if(x<0){ x=0; }else if(x>$(document).width()-$('div').outerWidth(true)){ x=$(document).width()-$('div').outerWidth(true); } if(y<0){ y=0 }else if(y>$(document).height()-$('div').outerHeight(true)){ y=$(document).height()-$('div').outerHeight(true); } $('div').css({ 'left':x+'px', 'top':y+'px' }); }); $(document).mouseup(function() { //unbind和off都可以解除绑定时间 $(document).unbind('mousemove'); }); }); });