jQuery jquery输入全选焦点

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3150275/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 14:55:41  来源:igfitidea点击:

jquery input select all on focus

jqueryinput

提问by Tim

I'm using this code to try and select all of the text in the field when a user focuses on the field. What happens is, it selects all for a second, then its unselected and the typing cursor is left where I clicked...

当用户专注于该字段时,我正在使用此代码尝试选择该字段中的所有文本。发生的情况是,它选择所有一秒钟,然后取消选择,并且键入光标留在我单击的位置...

$("input[type=text]").focus(function() {
   $(this).select();
});

I want it all to remain selected.

我希望这一切都保持选中状态。

回答by karim79

Try using clickinstead of focus. It seems to work for both mouse and key events (at least on Chrome/Mac):

尝试使用click代替focus. 它似乎适用于鼠标和按键事件(至少在 Chrome/Mac 上):

jQuery < version 1.7:

jQuery < 1.7 版:

$("input[type='text']").click(function () {
   $(this).select();
});

jQuery version 1.7+:

jQuery 1.7+ 版本:

$("input[type='text']").on("click", function () {
   $(this).select();
});

Here is a demo

这是一个演示

回答by Piskvor left the building

I think that what happens is this:

我认为发生的事情是这样的:

focus()
   UI tasks related to pre-focus
   callbacks
       select()
   UI tasks related to focus (which unselect again)

A workaround may be calling the select() asynchronously, so that it runs completely after focus():

解决方法可能是异步调用 select(),以便它在 focus() 之后完全运行:

$("input[type=text]").focus(function() { 
    var save_this = $(this);
    window.setTimeout (function(){ 
       save_this.select(); 
    },100);
});

回答by user2072367

I think this is better solution. Unlike simply selecting in onclick event, it doesn't prevent selecting/editing text with mouse. It works with major rendering engines including IE8.

我认为这是更好的解决方案。与简单地在 onclick 事件中选择不同,它不会阻止使用鼠标选择/编辑文本。它适用于包括 IE8 在内的主要渲染引擎。

$('input').on('focus', function (e) {
    $(this)
        .one('mouseup', function () {
            $(this).select();
            return false;
        })
        .select();
});

http://jsfiddle.net/25Mab/9/

http://jsfiddle.net/25Mab/9/

回答by animatedgif

There are some decent answers here and @user2072367 's is my favorite, but it has an unexpected result when you focus via tab rather than via click. ( unexpected result: to select text normally after focus via tab, you must click one additional time )

这里有一些不错的答案,@user2072367 是我最喜欢的,但是当您通过选项卡而不是单击来聚焦时,它会产生意想不到的结果。(意外的结果:要通过标签页获得焦点后正常选择文本,您必须多单击一次)

This fiddlefixes that small bug and additionally stores $(this) in a variable to avoid redundant DOM selection. Check it out! (:

这个小提琴修复了那个小错误,并另外将 $(this) 存储在一个变量中以避免冗余的 DOM 选择。一探究竟!(:

Tested in IE > 8

在 IE > 8 中测试

$('input').on('focus', function() {
    var $this = $(this)
        .one('mouseup.mouseupSelect', function() {
            $this.select();
            return false;
        })
        .one('mousedown', function() {
            // compensate for untriggered 'mouseup' caused by focus via tab
            $this.off('mouseup.mouseupSelect');
        })
        .select();
});

回答by KyleMit

After careful review, I propose this as a far cleaner solution within this thread:

经过仔细,我建议将此作为此线程中更清洁的解决方案:

$("input").focus(function(){
    $(this).on("click.a keyup.a", function(e){      
        $(this).off("click.a keyup.a").select();
    });
});

Demo in jsFiddle

jsFiddle 中的演示

The Problem:

问题:

Here's a little bit of explanation:

这里有一点解释:

First, let's take a look at the order of events when you mouse or tab into a field.
We can log all the relevant events like this:

首先,让我们看一下鼠标或 Tab 键进入字段时的事件顺序。
我们可以像这样记录所有相关事件:

$("input").on("mousedown focus mouseup click blur keydown keypress keyup change",
              function(e) { console.log(e.type); });

focus events

focus events

Note: I've changed this solution to use clickrather than mouseupas it happens later in the event pipeline and seemed to be causing some issues in firefox as per @Jocie's comment

注意:我已将这个解决方案更改为使用,click而不是mouseup在事件管道的后期发生,并且根据@Jocie 的评论,似乎在 firefox 中引起了一些问题

Some browsers attempt to position the cursor during the mouseupor clickevents. This makes sense since you might want to start the caret in one position and drag over to highlight some text. It can't make a designation about the caret position until you have actually lifted the mouse. So functions that handle focusare fated to respond too early, leaving the browser to override your positioning.

某些浏览器尝试在mouseupclick事件期间定位光标。这是有道理的,因为您可能希望在一个位置开始插入符号并拖动以突出显示某些文本。在您真正抬起鼠标之前,它无法指定插入符号的位置。所以处理函数focus注定会过早响应,让浏览器覆盖你的定位。

But the rub is that we really do want to handle the focus event. It lets us know the first time that someone has entered the field. After that point, we don't want to continue to override user selection behavior.

但问题是我们确实想要处理焦点事件。它让我们第一次知道有人进入该领域。在那之后,我们不想继续覆盖用户选择行为。

The Solution:

解决方案:

Instead, within the focusevent handler, we can quickly attach listeners for the click(click in) and keyup(tab in) events that are about to fire.

相反,在focus事件处理程序中,我们可以为即将触发的click(click in) 和keyup(tab in) 事件快速附加侦听器。

Note: The keyup of a tab event will actually fire in the new input field, not the previous one

注意:tab 事件的 keyup 实际上会在新的输入字段中触发,而不是前一个

We only want to fire the event once. We could use .one("click keyup), but this would call the event handler once for each event type. Instead, as soon as either mouseup or keyup is pressed we'll call our function. The first thing we'll do, is remove the handlers for both. That way it won't matter whether we tabbed or moused in. The function should execute exactly once.

我们只想触发一次事件。我们可以使用.one("click keyup),但这会为每个事件类型调用一次事件处理程序。相反,只要按下 mouseup 或 keyup,我们就会调用我们的函数。我们要做的第一件事是删除两者的处理程序。那样的话,我们是用 Tab 键还是鼠标进入都没有关系。该函数应该只执行一次。

Note: Most browsers naturally select all text during a tab event, but as animatedgif pointed out, we still want to handle the keyupevent, otherwise the mouseupevent will still be lingering around anytime we've tabbed in. We listen to both so we can turn off the listeners as soon as we've processed the selection.

注意:大多数浏览器会在 tab 事件期间自然地选择所有文本,但正如animationgif 指出的那样,我们仍然希望处理该keyup事件,否则mouseup无论何时我们加入 tab 事件,该事件仍然会徘徊不去。一旦我们处理了选择,就立即关闭听众。

Now, we can call select()after the browser has made its selection so we're sure to override the default behavior.

现在,我们可以select()在浏览器做出选择后调用,以便我们确保覆盖默认行为。

Finally, for extra protection, we can add event namespacesto the mouseupand keyupfunctions so the .off()method doesn't remove any other listeners that might be in play.

最后,为了额外的保护,我们可以向和函数添加事件命名空间,这样该方法就不会删除任何其他可能正在运行的侦听器。mouseupkeyup.off()



Tested in IE 10+, FF 28+, & Chrome 35+

在 IE 10+、FF 28+ 和 Chrome 35+ 中测试



Alternatively, if you want to extend jQuery with a function called oncethat will fire exactly once for any number of events:

或者,如果您想使用一个函数once来扩展 jQuery,该函数将为任意数量的事件触发一次

$.fn.once = function (events, callback) {
    return this.each(function () {
        var myCallback = function (e) {
            callback.call(this, e);
            $(this).off(events, myCallback);
        };
        $(this).on(events, myCallback);
    });
};

Then you can simplify the code further like this:

然后你可以像这样进一步简化代码:

$("input").focus(function(){
    $(this).once("click keyup", function(e){      
        $(this).select();
    });
});

Demo in fiddle

小提琴演示

回答by Nianpeng

This would do the work and avoid the issue that you can no longer select part of the text by mouse.

这将完成工作并避免您无法再通过鼠标选择部分文本的问题。

$("input[type=text]").click(function() {
    if(!$(this).hasClass("selected")) {
        $(this).select();
        $(this).addClass("selected");
    }
});
$("input[type=text]").blur(function() {
    if($(this).hasClass("selected")) {
        $(this).removeClass("selected");
    }
});

回答by anihilnine

This version works on ios and also fixes standard drag-to-select on windows chrome

此版本适用于 ios,还修复了 windows chrome 上的标准拖动选择

var srcEvent = null;

$("input[type=text],input[type=number]")

    .mousedown(function (event) {
        srcEvent = event;
    })

    .mouseup(function (event) {
        var delta = Math.abs(event.clientX - srcEvent.clientX) 
                  + Math.abs(event.clientY - srcEvent.clientY);

        var threshold = 2;
        if (delta <= threshold) {
                   try {
                        // ios likes this but windows-chrome does not on number fields
                        $(this)[0].selectionStart = 0;
                        $(this)[0].selectionEnd = 1000;
                    } catch (e) {
                        // windows-chrome likes this
                        $(this).select();
                    }
        }
    });

http://jsfiddle.net/Zx2sc/2/

http://jsfiddle.net/Zx2sc/2/

回答by Colin Breame

The problem with most of these solutions is that they do not work correctly when changing the cursor position within the input field.

大多数这些解决方案的问题在于,它们在更改输入字段内的光标位置时无法正常工作。

The onmouseupevent changes the cursor position within the field, which is fired after onfocus(at least within Chrome and FF). If you unconditionally discard the mouseupthen the user cannot change the cursor position with the mouse.

onmouseup事件会更改字段内的光标位置,该位置会在之后onfocus(至少在 Chrome 和 FF 中)被触发。如果您无条件放弃,mouseup则用户无法使用鼠标更改光标位置。

function selectOnFocus(input) {
    input.each(function (index, elem) {
        var jelem = $(elem);
        var ignoreNextMouseUp = false;

        jelem.mousedown(function () {
            if (document.activeElement !== elem) {
                ignoreNextMouseUp = true;
            }
        });
        jelem.mouseup(function (ev) {
            if (ignoreNextMouseUp) {
                ev.preventDefault();
                ignoreNextMouseUp = false;
            }
        });
        jelem.focus(function () {
            jelem.select();
        });
    });
}
selectOnFocus($("#myInputElement"));

The code will conditionally prevent the mouseupdefault behaviour if the field does not currently have focus. It works for these cases:

mouseup如果该字段当前没有焦点,代码将有条件地阻止默认行为。它适用于这些情况:

  • clicking when field is not focused
  • clicking when field has focus
  • tabbing into the field
  • 当字段未聚焦时单击
  • 当字段具有焦点时单击
  • 进入该领域

I have tested this within Chrome 31, FF 26 and IE 11.

我已经在 Chrome 31、FF 26 和 IE 11 中对此进行了测试。

回答by RafaelTSCS

Found a awesome solution reading this thread

阅读此线程找到了一个很棒的解决方案

$(function(){

    jQuery.selectText('input:text');
    jQuery.selectText('input:password');

});

jQuery.extend( {
    selectText: function(s) { 
        $(s).live('focus',function() {
            var self = $(this);
            setTimeout(function() {self.select();}, 0);
        });
    }
});

回答by Aaron

I'm coming from late 2016 and this code just works in recent versions of jquery (jquery-2.1.3.js in this case).

我来自 2016 年末,此代码仅适用于最新版本的 jquery(在本例中为 jquery-2.1.3.js)。

if ($(element).is("input")) {
    $(element).focus(function () {
        $(element).select();
    });
}