我正在为我支持的项目制作一个可拖动的div元素。我发现这个AngularJS directive允许元素可拖动。
我修改了指令以更改起始位置,但是当我进行更改时,鼠标方向没有反转(即将鼠标向右移动,div移动到左侧)。以下是AngularJS directive的更新版本,其中包含以下更改,以展示我遇到的问题。
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
});
app.directive('ngDraggable', function($document, $window){
function makeDraggable(scope, element, attr) {
var startX = 0;
var startY = 0;
var x = 20;
var y = 20;
// Start with a random pos
// var x = Math.floor((Math.random() * 500) + 40);
// var y = Math.floor((Math.random() * 360) + 40);
element.css({
position: 'absolute',
cursor: 'pointer',
bottom: y + 'px',
right: x + 'px'
});
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({
bottom: y + 'px',
right: x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
return {
link: makeDraggable
};
});
答案 0 :(得分:1)
我不确定你的指令有什么问题,但是在拖拽工作之后为你的元素的css提供负值。
element.css({
bottom: -y + 'px',
right: -x + 'px'
});
检查codepen。
参考代码:
var app = angular.module('myApp', []);
app.controller('myController', function($scope) {
});
app.directive('ngDraggable', function($document, $window) {
function makeDraggable(scope, element, attr) {
var startX = 0;
var startY = 0;
var x = 20;
var y = 20;
// Start with a random pos
// var x = Math.floor((Math.random() * 500) + 40);
// var y = Math.floor((Math.random() * 360) + 40);
element.css({
position: 'absolute',
cursor: 'pointer',
bottom: y + 'px',
right: x + 'px'
});
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({
bottom: -y + 'px',
right: -x + 'px'
});
}
function mouseup() {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
}
}
return {
link: makeDraggable
};
});

img {
height: 100px;
}
span {
background-color: rgba(255, 255, 255, 0.5);
display: inline-block;
font: 20px/28px Georgia, serif;
padding: 5px;
}

<html ng-app='myApp'>
<head>
<title>ng-draggable</title>
<script src="http://code.angularjs.org/1.2.9/angular.min.js"></script>
</head>
<body>
<div ng-controller="myController">
<h2>Dragging directive fun</h2>
<img ng-draggable src="http://fc00.deviantart.net/fs70/i/2012/135/a/7/tux_button_by_blacklite_teh_haxxor-d4zv3fv.png" />
</div>
</body>
</html>
&#13;