//html代码部分 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <script src="../js/jquery-1.11.1.js"></script> </head> <style> body{ padding: 0; margin: 0; } .w{ width: 600px; height: 600px; background-color: red; position: absolute; left: 0; top: 0; } .a{ width: 600px; height: 50px; cursor: move; background-color: yellowgreen; position: absolute; left: 0; top:0; } </style> <body> <div class="w"> <div class="a"></div> </div> </body></html>
//需要拖动的部分需加上定位属性
//jquery代码部分 <script> //鼠标拖拽效果 (function($){ $.fn.wwp_tz = function(opt){ var defaults = { }; var options = $.extend({},defaults,opt); this.each(function(){ var $this = $(this); var L=0,T=0; $this.mousedown(function(event){ $this.data("down","1"); var X = event.clientX; //获取当前鼠标的X轴; var Y = event.clientY; //获取当前鼠标的Y轴; var offset = $this.offset(); var box_x = offset.left; //获取当前元素的x轴浮动距离; var box_y = offset.top; //获取当前元素的y轴浮动距离; L = X-box_x; //当前鼠标到元素之间的距离; T = Y-box_y; }).mousemove(function(event){ if($this.data("down") == 1){ var X = event.clientX; //获取当前鼠标的X轴; var Y = event.clientY; //获取当前鼠标的Y轴; var box_left = X-L; //鼠标当前位置减去鼠标到元素的位置 var box_top = Y-T; if(options.dom == 1){ $this.css({left:box_left+"px",top:box_top+"px"}) }else if(options.dom == 2){ $this.parent().css({left:box_left+"px",top:box_top+"px"}) } }else{ return false; } }).mouseup(function(){ //鼠标抬起时 $this.data("down","-1"); }).mouseleave(function(){ //光标离开元素时 $this.data("down","-1"); }); }) } })(jQuery); //调用 $(function(){ $(".a").wwp_tz({ dom:2 // 1是元素自身拖动,2是含父节点一起拖动 }) }); </script>
时间: 2024-10-20 14:33:00