本文翻译自:jquery input select all on focus
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. 我希望这一切都保持选中状态。
参考:https://stackoom.com/question/DDWt/jquery输入在焦点上选择全部
i using FF 16.0.2 and jquery 1.8.3, all the code in the answer didn't work. 我使用FF 16.0.2和jquery 1.8.3,答案中的所有代码都不起作用。
I use code like this and work. 我使用这样的代码并且工作。
$("input[type=text]").focus().select();
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);
});
}
});
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");
}
});
I think this is better solution. 我认为这是更好的解决方案。 Unlike simply selecting in onclick event, it doesn't prevent selecting/editing text with mouse. 与简单地选择onclick事件不同,它不会阻止使用鼠标选择/编辑文本。 It works with major rendering engines including IE8. 它适用于包括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/
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). onmouseup
事件会更改字段内的光标位置,该位置在onfocus
之后触发(至少在Chrome和FF中)。 If you unconditionally discard the mouseup
then the user cannot change the cursor position with the mouse. 如果无条件丢弃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 mouseup
default behaviour if the field does not currently have focus. 如果该字段当前没有焦点,则代码将有条件地阻止mouseup
默认行为。 It works for these cases: 它适用于以下情况:
I have tested this within Chrome 31, FF 26 and IE 11. 我在Chrome 31,FF 26和IE 11中测试了这个。