选择输入焦点上的文本 [英] Select text on input focus
问题描述
我有一个文本输入.当输入获得焦点时,我想选择输入中的文本.
I have a text input. When the input receives focus I want to select the text inside of the input.
使用 jQuery 我会这样做:
With jQuery I'd do it this way:
<input type="text" value="test" />
$("input[type=text]").click(function() {
$(this).select();
// would select "test" in this example
});
我四处寻找试图找到 Angular 的方式,但我发现的大多数示例都在处理一个指令,该指令正在观察模式属性的变化.我假设我需要一个指令来观察接收焦点的输入.我该怎么做?
I've searched around to try and find the Angular way but most examples I'm finding are dealing with a directive that is watching a modal property for a change. I'm assuming I need a directive that is watching for an input that receives focus. How would I do that?
推荐答案
在 Angular 中执行此操作的方法是创建一个自定义指令,为您执行自动选择.
The way to do this in Angular is to create a custom directive which does the autoselect for you.
module.directive('selectOnClick', ['$window', function ($window) {
return {
restrict: 'A',
link: function (scope, element, attrs) {
element.on('click', function () {
if (!$window.getSelection().toString()) {
// Required for mobile Safari
this.setSelectionRange(0, this.value.length)
}
});
}
};
}]);
像这样应用指令:
<input type="text" value="test" select-on-click />
Update1:删除了 jQuery 依赖项.
Update1: Removed jQuery dependency.
Update2:限制为属性.
Update3:适用于移动版 Safari.允许选择部分文本(需要 IE>8).
Update3: Works in mobile Safari. Allows selecting part of the text (requires IE>8).
这篇关于选择输入焦点上的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!