我目前正在尝试重构一些非常简单的AngularJS代码,以便在顶级指令下移动所有功能。父元素被赋予指令,该指令将'mousemove'事件绑定到该元素,然后通过具有特定ID的每个子节点并将'mousedown'和'mouseup'事件回调绑定到它。
angular.module('DataStructureVisualizer').
directive('dragDrop', function () {
return {
link: function ($scope, element, attrs) {
var mouseLocX = 0;
var mouseLocY = 0;
var isElementHeldDown = false;
var elementHeldDown;
var heldDownElementWidth = 0;
var heldDownElementHeight = 0;
//Bind callback to get mouse position
$scope.captureCoordinate = function($event) {
mouseLocX = $event.x;
mouseLocY = $event.y;
if(isElementHeldDown == true) {
elementHeldDown.css('position', 'absolute');
elementHeldDown.css('left', mouseLocX - heldDownElementWidth / 2 + 'px');
elementHeldDown.css('top', mouseLocY - heldDownElementHeight / 2 + 'px');
}
}
var dragDroppables = element[0].querySelectorAll('#DragDroppable');
for (var elementIdx = 0; elementIdx < dragDroppables.length; elementIdx++) {
var bindElement = dragDroppables[elementIdx];
bindElement.on('mousedown', function() {
element.css('background-color', 'rgb(17, 83, 252)');
elementHeldDown = element;
isElementHeldDown = true;
var style = window.getComputedStyle(element[0]);
heldDownElementWidth = parseInt(style.getPropertyValue('width'));
heldDownElementHeight = parseInt(style.getPropertyValue('height'));
});
bindElement.on('mouseup', function () {
element.css('background-color', 'rgb(73, 122, 255)');
isElementHeldDown = false;
});
}
我能够完美地绑定到元素,但是当使用element.querySelectorAll并浏览返回的元素列表时,它会返回并说“bindElement.on()不是函数”
这是HTML方面:
<div id="DragDropArea" ng-mousemove="captureCoordinate($event)" drag-drop>
<!-- <div>x: {{x}}</div>
<div>y: {{y}}</div> -->
<div id="DragDroppable">
<div line-draw>64</div>
</div>
<div id="DragDroppable">
<div line-draw>64</div>
</div>
</div>
答案 0 :(得分:0)
这个答案在于,当抓取子元素时,它返回一个NodeList的NodeList,当它们需要是jQuery或jqLite样式对象时。改变
bindElement.on('mousedown', function() {...
要
angular.element(bindElement).on('mousedown', function() {...
解决了问题。