我有一个 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();
});
}
};
})
它运行良好,但我不希望当用户从控件中 focusout
并再次 focusin
时也选择它的文本。它应该只选择一次文本(而不是第二个焦点)。
另外,当所有文本都被选中时,如何从元素中移除焦点?
最佳答案
您可以创建一个变量,如果元素被选中,该变量将保存 bool 值,并且仅当元素尚未被选中时才选择该元素。像这样:
.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();
});
}
};
})
关于javascript - 选择元素中的文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45434308/