<!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=utf-8" /> <title>无标题文档</title> <style> #drigging { width:200px; background:#ccc; border:solid 1px #666; height:80px; line-height:80px; text-align:center; position:absolute; } </style> <script src="jquery-1.8.2.min.js" type="text/javascript"></script> <script type="text/javascript"> $(function(){ var bool=false; //标识是否移动元素 var offsetx=0; //声明p在当前窗口的left值 var offsety=0; //声明p在当前窗口的top值 $(#drigging).mouseover(function(){ $(this).css('cursor','move'); //当鼠标移动到拖拽的p上的时候,将鼠标的样式设置为移动(move) }) $(#drigging).mousedown(function(){ bool=true; //当鼠标在移动元素按下的时候将bool设定为true offsetx = event.offsetx; //获取鼠标在当前窗口的相对偏移位置的left值并赋值给offsetx offsety = event.offsety; //获取鼠在当前窗口的相对偏移位置的top值并赋值给offsety $(this).css('cursor','move'); }).mouseup(function(){ bool=false; //当鼠标在移动元素起来的时候将bool设定为false }) $(document).mousemove(function(){ if(!bool)//如果bool为false则返回 return; //当bool为true的时候执行下面的代码 var x = event.clientx-offsetx; //event.clientx得到鼠标相对于客户端正文区域的偏移 //然后减去offsetx即得到当前推拽元素相对于当前窗口的x值 //(减去鼠标刚开始拖动的时候在当前窗口的偏移x) var y = event.clienty-offsety; //event.clienty得到鼠标相对于客户端正文区域的偏移 //然后减去offsetx即得到当前推拽元素相对于当前窗口的y值 //(减去鼠标刚开始拖动的时候在当前窗口的偏移y) $(#drigging).css(left, x); $(#drigging).css(top, y); $(#drigging).css('cursor','move'); }) }) </script> </head> <body> <p id="drigging" style="float:left"> 拖拽层 </p> </body> </html>
相信看了本文案例你已经掌握了方法,更多精彩请关注其它相关文章!
推荐阅读:
json操作日期格式
jsonp怎样才能解决ajax跨域
不使用插件让ajax实现异步刷新
以上就是jquery实现div拖拽效果功能(附代码)的详细内容。
