鼠标拖动DOM

时间:2021-01-14 07:53:38

自己收藏,使用angualrjs的directive些的鼠标拖动DOM....

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>鼠标拖动div</title>
<script src="http://apps.bdimg.com/libs/angular.js/1.4.6/angular.min.js"></script>
<script>
(function(){
angular.module('app',[])
.directive('ngDirective', ['$document', function($document){
return {
link: function link(scope, element, attrs){
var startX = 0, startY = 0, x = 0, y = 0;
element.css({
position: 'relative',
border: '1px solid red',
backgroundColor: '#ccc',
cursor: 'pointer',
width:'100px',
height:'100px'
});
element.on('mousedown', function(event){
event.preventDefault();
startX = event.pageX - x;
startY = event.pageY - y;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
});
function mousemove(event) {
y = event.pageY - startY;
x = event.pageX - startX;
element.css({
top: y + 'px',
left: x + 'px'
});
};
function mouseup() {
$document.off('mousemove', mousemove);
$document.off('mouseup', mouseup);
}
}
}
}])
})()
</script>
</head>
<body ng-app="app">
<div ng-directive>DONE</div>
</body>
</html>