【问题标题】:Select text in element选择元素中的文本
【发布时间】:2018-01-08 02:42:59
【问题描述】:

我有一个 input 元素,它使用 ng-model 在其中包含文本,然后我尝试通过创建自定义侦探来选择所有文本:

.directive('selectText', function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            elem.bind('focus', function() {
                $(elem).select();
            });
            scope.$watch("edit",function(newValue,oldValue) {
                $(elem).select();
            });
        }
    };
})

它运行良好,但我不希望当用户foucusout 来自控件并再次选择focusin 时也选择它的文本。它应该只选择一次文本(而不是第二个焦点)。 另外,当所有文本都被选中时,如何从元素中移除焦点?

【问题讨论】:

  • 你想在选择所有文本后立即聚焦吗?还是别的什么?

标签: javascript jquery angularjs angular-directive


【解决方案1】:

您可以创建一个变量,如果元素被选中,则该变量将保存布尔值,并且仅在元素尚未被选中时才选择元素。像这样:

.directive('selectText', function() {
    return {
        require: 'ngModel',
        link: function(scope, elem, attrs, ctrl) {
            var selected = false;
            elem.bind('focus', function() {
                if (!selected) {
                    $(elem).select();
                    selected = true;
                }
            });
            scope.$watch("edit",function(newValue,oldValue) {
                $(elem).select();
            });
        }
    };
})

【讨论】:

  • 没有“加载”、“显示”等事件...?
【解决方案2】:

function Ctrl3($scope) {
  $scope.title = 'My relevant title';
}

angular.module('scopePropertiesModule', [])
  .directive('selectText', function() {
    return {
      require: 'ngModel',
      link: function(scope, elem, attrs, ctrl) {
        var counter = 0;
        elem.bind('focus', function() {
          console.log(counter)

          if (counter < 1) {
            $(elem).select();
            /*setTimeout(function() {
              $(elem).blur();
            }, 1000);*/
            
            counter++;
          }
        });
        scope.$watch("edit", function(newValue, oldValue) {
          $(elem).select();
        });
      }
    };
  })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.9/angular.min.js"></script>
<div ng-app="scopePropertiesModule">
  <div ng-controller="Ctrl3">
    <input select-text ng-model="title">
  </div>
</div>

检查一下。

【讨论】:

    猜你喜欢
    • 2015-08-05
    • 2011-03-11
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2023-03-16
    • 2021-09-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多