【问题标题】:Cannot bind event callbacks on DOM objects under a directive's DOM element无法在指令的 DOM 元素下绑定 DOM 对象上的事件回调
【发布时间】:2018-05-03 06:12:08
【问题描述】:

我目前正在尝试重构一些非常简单的 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>

【问题讨论】:

  • 这是因为bindElementElement,而不是jQuery 或jqLit​​e 样式对象。
  • 我相信angular.element(bindElement).on('mousedown', function() {... 会起作用(没有测试你上面的指令)
  • @davidkonrad 成功了 - 谢谢!

标签: javascript jquery html angularjs dom


【解决方案1】:

这个答案在于,当抓取子元素时,它会返回一个元素的 NodeList,而这些元素需要是 jQuery 或 jqLit​​e 样式的对象。改变

bindElement.on('mousedown', function() {...

angular.element(bindElement).on('mousedown', function() {...

解决了问题。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-29
    • 2011-08-16
    • 2022-12-14
    • 2012-10-08
    • 2012-12-12
    • 1970-01-01
    • 2012-10-22
    • 1970-01-01
    相关资源
    最近更新 更多