在输入焦点选择文本 [英] Select text on input focus

查看:141
本文介绍了在输入焦点选择文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本输入。当输入获得焦点我要选择输入中的文本。

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
});

我四处寻找,试图找到该角的方式,但大多数的例子我发现现在处理的是看一换模态特性的指令。我假设我需要的是看对接收焦点的输入指令。我会怎么做呢?

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?

推荐答案

在角做到这一点的方法是创建由它来自动选择适合你的自定义指令。

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆