0
我有這個jsfiddle,它使用了一個angularjs指令來拖放一個白色正方形。這個新的重複拖放指令有什麼問題?
我又增加了綠化廣場和複製的指令。正方形不能再拖放到第二個jsfiddle中。代碼有什麼問題? Fiddle 2
我改變的地方是; 在HTML
<div class="shapeX" ng-draggableX='dragOptions'></div>
在CSS中,
.shapeX
{
position: absolute;
width : 40px;
height: 40px;
background-color: green;
}
在JavaScript(只需複製並粘貼原來的指令,並重新命名),
.directive('ngDraggableX', function($document) {
return {
restrict: 'A',
scope: {
dragOptions: '=ngDraggable'
},
link: function(scope, elem, attr) {
var startX, startY, x = 0, y = 0,
start, stop, drag, container;
var width = elem[0].offsetWidth,
height = elem[0].offsetHeight;
// Obtain drag options
if (scope.dragOptions) {
start = scope.dragOptions.start;
drag = scope.dragOptions.drag;
stop = scope.dragOptions.stop;
var id = scope.dragOptions.container;
if (id) {
container = document.getElementById(id).getBoundingClientRect();
}
}
// Bind mousedown event
elem.on('mousedown', function(e) {
e.preventDefault();
startX = e.clientX - elem[0].offsetLeft;
startY = e.clientY - elem[0].offsetTop;
$document.on('mousemove', mousemove);
$document.on('mouseup', mouseup);
if (start) start(e);
});
// Handle drag event
function mousemove(e) {
y = e.clientY - startY;
x = e.clientX - startX;
setPosition();
if (drag) drag(e);
}
// Unbind drag events
function mouseup(e) {
$document.unbind('mousemove', mousemove);
$document.unbind('mouseup', mouseup);
if (stop) stop(e);
}
// Move element, within container if provided
function setPosition() {
if (container) {
if (x < container.left) {
x = container.left;
} else if (x > container.right - width) {
x = container.right - width;
}
if (y < container.top) {
y = container.top;
} else if (y > container.bottom - height) {
y = container.bottom - height;
}
}
elem.css({
top: y + 'px',
left: x + 'px'
});
}
}
}
})
謝謝!驗證是正確的答案。下面是工作jsfiddle。 http://jsfiddle.net/helpme128/yrdce2qr/2/ – user781486
我從來不知道angularjs的這方面。 ng-draggable-x(這個連字符)是一個angularjs指令的約定嗎? – user781486
看到它。 https://docs.angularjs.org/guide/directive 正常化。 – user781486