选择文本或拖动时,单击触发

时间:2014-11-05 18:55:06

标签: javascript angularjs angularjs-ng-click

使用ng-click div:

<div ng-click="doSomething()">bla bla</div>
即使用户仅选择或拖动div,

ng-click也会触发。如何在仍然启用文本选择的同时防止这种情况?

2 个答案:

答案 0 :(得分:2)

在要求类似的东西时,在一个应该响应ngClick的元素上需要通常的文本选择行为,我编写了以下指令,这可能是有用的:

.directive('selectableText', function($window, $timeout) {
  var i = 0;      
  return {
    restrict: 'A',
    priority:  1,
    compile: function (tElem, tAttrs) {
      var fn = '$$clickOnNoSelect' + i++,
          _ngClick = tAttrs.ngClick;

      tAttrs.ngClick = fn + '($event)';

      return function(scope) {
        var lastAnchorOffset, lastFocusOffset, timer;

        scope[fn] = function(event) {
          var selection    = $window.getSelection(),
              anchorOffset = selection.anchorOffset,
              focusOffset  = selection.focusOffset;

          if(focusOffset - anchorOffset !== 0) {
            if(!(lastAnchorOffset === anchorOffset && lastFocusOffset === focusOffset)) {
              lastAnchorOffset = anchorOffset;
              lastFocusOffset  = focusOffset;
              if(timer) {
                $timeout.cancel(timer);
                timer = null;
              }
              return;
            }
          }
          lastAnchorOffset = null;
          lastFocusOffset  = null;

          // delay invoking click so as to watch for user double-clicking 
          // to select words
          timer = $timeout(function() {
            scope.$eval(_ngClick, {$event: event});  
            timer = null;
          }, 250);
        };
      };
    }
  };
});

Plunker:http://plnkr.co/edit/kkfXfiLvGXqNYs3N6fTz?p=preview

答案 1 :(得分:1)

我也必须处理这个问题,并提出了一些更简单的方法。基本上你将x位置存储在mousedown上,然后在mouseup上比较新的x位置:

ng-mousedown="setCurrentPos($event)"
ng-mouseup="doStuff($event)"

函数setCurrentPos():

var setCurrentPos = function($event) {
  $scope.currentPos = $event.offsetX;
}

函数doStuff():

var doStuff = function ($event) {
  if ($event.offsetX == $scope.currentPos) {
    // Only do stuff here, when mouse was NOT dragged
  } else {
    // Do other stuff, which includes mouse dragging
  }
}