【问题标题】:AngularJS: ng-click and select textAngularJS:ng-click 并选择文本
【发布时间】:2015-11-10 22:28:22
【问题描述】:

在我的应用中,我在点击元素后使用了一些逻辑。

例如:

html

<h3 ng-click="showAlert('text')">this is text! (try to click and select)</h3>

js

$scope.showAlert = function(text) {
  console.log('click!');
};

当我点击元素时:一切正常。正如预期的那样,一切都完成了。

但是!

为什么,当我尝试选择文本时,我的事件也会被触发?

如何跳过选择事件?

plunker:click

【问题讨论】:

  • 没有单独的选择事件 - 所以无论如何点击都会触发。您可以对当前选择等进行一些检查。但我觉得这一切都很难奏效。顺便说一句,点击文字是如此不自然的行为......
  • @PetrAveryanov 例如切换编辑器(如jira do)
  • y,好吧,忘了 texteditables)

标签: javascript jquery html angularjs


【解决方案1】:

您可以获取mousedownmouseup 之间的时间,以确定是点击还是选择了文本。

像这样: Demo

(function(){
  angular.module("app", []);

  angular.module("app")
  .directive("noclick", function(){
    return {
      restrict: "A",
      link: function(scope, element, attr){
        scope.time= Date.now();

        element.on("mousedown mouseup", function(e){
          if(e.type == "mousedown"){
            scope.time= Date.now();
          }

          if(e.type == "mouseup"){
            if(Date.now() - scope.time> 300){
              return false;
            }else{
              console.log("clicked");
            }
          }
        });
      }
    }
  });
})(window, angular);

注意:我在这种情况下使用指令。

【讨论】:

  • 我会设置 100 毫秒,反正 +1
  • 如果我慢慢按下鼠标按钮 -> 没有点击(可能你也想比较坐标......反正闻起来很糟糕)
  • @MaximShoustin,是的,我在画布游戏中使用了 300,不过对于这种情况,100 更好。谢谢。
  • @PetrAveryanov,有多慢?
  • 这确实很干净,但更强大的版本是检查鼠标移动而不是时间。这种方式点击的工作方式与其他地方一样。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-09-09
相关资源
最近更新 更多