<!DOCTYPE HTML> <html ng-app="myApp"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>无标题文档</title> <style> #div1{ 100px;height: 100px;background: red;position: absolute; } </style> <script type="text/javascript" src="jquery-1.11.1.js"></script> <script src="angular.min.js"></script> <script> var m1 = angular.module('myApp',[]); m1.controller('Aaa',['$scope',function($scope){ }]); m1.directive('myDrag',function (){ return { restrict:'A', link:function(scope,element,attr){ var disX = 0; var disY = 0; attr.myDrag = angular.equals(attr.myDrag,'true'); element.on('mousedown',function (ev){ var This = this; disX = ev.pageX - $(this).offset().left; disY = ev.pageY - $(this).offset().top; if(attr.myDrag){ var $line = $('<div>'); $line.css({$(this).outerWidth(),height:$(this).outerHeight(),border:'1px gray dotted',position:'absolute',left:$(this).offset().left,top:$(this).offset.top,position:'absolute'}); $('body').append($line); } $(document).on('mousemove',function(ev){ if(attr.myDrag){ $line.css('left',ev.pageX - disX); $line.css('top',ev.pageY - disY); }else{ $(This).css('left',ev.pageX - disX); $(This).css('top',ev.pageY - disY); } }); $(document).on('mouseup',function(){ $(document).off(); if(attr.myDrag){ $(This).css('left',$line.offset().left); $(This).css('top',$line.offset().top); $line.remove(); } }) return false; }) } } }) </script> </head> <body ng-controller="Aaa"> <div id="div1" my-drag='true'></div> </body> </html>