jquery 输入全选焦点

发布于 2024-09-07 07:03:03 字数 196 浏览 3 评论 0原文

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

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

我希望所有内容都保持选中状态。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(17

神妖 2024-09-14 07:03:04
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>
一梦浮鱼 2024-09-14 07:03:03

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

jQuery <版本 1.7:

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

jQuery 版本 1.7+:

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

这是一个演示

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

jQuery < version 1.7:

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

jQuery version 1.7+:

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

Here is a demo

寒冷纷飞旳雪 2024-09-14 07:03:03

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

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

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

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

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():

$("input[type=text]").focus(function() { 
    var save_this = $(this);
    window.setTimeout (function(){ 
       save_this.select(); 
    },100);
});
兮子 2024-09-14 07:03:03

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

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

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

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.

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

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

呆橘 2024-09-14 07:03:03

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

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

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

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 )

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

Tested in 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();
});
箜明 2024-09-14 07:03:03

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

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

JSFiddle 中的演示

问题:

这是一点解释:

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

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

焦点事件

注意:我已更改此解决方案以使用 click 而不是 mouseup,因为它稍后会在事件管道中发生,并且似乎是根据 @Jocie 的评论,在 Firefox 中造成一些问题

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

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

解决方案:

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

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

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

注意:大多数浏览器自然会在选项卡事件期间选择所有文本,但正如 animatedgif 指出的,我们仍然想要处理 keyup 事件,否则 mouseup 事件在我们按下 Tab 键时仍然会徘徊。我们监听这两个事件,以便我们可以将我们处理完选择后立即关闭听众。


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

最后,为了提供额外的保护,我们可以将 事件命名空间 添加到mouseupkeyup 函数,因此 .off() 方法不会删除可能正在播放的任何其他侦听器。


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


或者,如果您想使用 名为 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);
    });
};

那么你可以进一步简化代码,如下所示:

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

小提琴演示

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

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:

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

focus events

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

Some browsers attempt to position the cursor during the mouseup or click events. 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 focus are fated to respond too early, leaving the browser to override your positioning.

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 focus event handler, we can quickly attach listeners for the click (click in) and keyup (tab in) events that are about to fire.

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

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.

Note: Most browsers naturally select all text during a tab event, but as animatedgif pointed out, we still want to handle the keyup event, otherwise the mouseup event 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.

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

Finally, for extra protection, we can add event namespaces to the mouseup and keyup functions so the .off() method doesn't remove any other listeners that might be in play.


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


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

$.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

萌面超妹 2024-09-14 07:03:03

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

$("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");
    }
});

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");
    }
});
节枝 2024-09-14 07:03:03

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

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

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

  • 当字段未获得焦点时单击
  • 单击当字段具有焦点时
  • 按 Tab 键进入字段

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

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

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

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 mouseup default behaviour if the field does not currently have focus. It works for these cases:

  • 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.

风渺 2024-09-14 07:03:03

此版本适用于 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/

This version works on ios and also fixes standard drag-to-select on 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/

笑红尘 2024-09-14 07:03:03

阅读此帖子找到了一个很棒的解决方案

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

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);
        });
    }
});
寄居人 2024-09-14 07:03:03

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

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

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

if ($(element).is("input")) {
    $(element).focus(function () {
        $(element).select();
    });
}
北方的巷 2024-09-14 07:03:03

我总是使用 requestAnimationFrame() 来跳过内部事件后机制,这在 Firefox 中完美运行。尚未在 Chrome 中进行测试。

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

I always use requestAnimationFrame() to jump over internal post-event mechanisms and this works perfectly in Firefox. Haven't tested in Chrome.

$("input[type=text]").on('focus', function() {
    requestAnimationFrame(() => $(this).select());
});
年华零落成诗 2024-09-14 07:03:03

或者您可以只使用 效果很好。

Or you can just use <input onclick="select()"> Works perfect.

醉城メ夜风 2024-09-14 07:03:03
var timeOutSelect;
$("input[type=text]").focus(function() { 
        var save_this = $(this);
        clearTimeout(timeOutSelect);
        timeOutSelect = window.setTimeout (function(){ 
                save_this.select(); 
        }, 100);
});

如果您在两个输入之间快速切换,请使用clearTimeout以提高安全性。
clearTimeout 清除旧的超时...

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

Use clearTimeout for more security if you switch quickly between two input..
clearTimeout clean the old timeout...

妥活 2024-09-14 07:03:03

您可以使用简单的代码:

$('#idname').select();

You can use simple code:

$('#idname').select();
爱给你人给你 2024-09-14 07:03:03

与原生 JavaScript select() 配合得很好。

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

或者一般来说:

$("input[type=text]")[0].select()

Works great with the native JavaScript select().

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

or in general:

$("input[type=text]")[0].select()
星星的軌跡 2024-09-14 07:03:03

我使用 FF 16.0.2 和 jquery 1.8.3,答案中的所有代码都不起作用。
我使用这样的代码并工作。

$("input[type=text]").focus().select();

i using FF 16.0.2 and jquery 1.8.3, all the code in the answer didn't work.
I use code like this and work.

$("input[type=text]").focus().select();
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文