什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
我在某个地方播种了这个,工作得很完美!
$('input').on('focus', function (e) {
$(this)
$(element).one('mouseup', function () {
$(this).select();
return false;
}) .select();
});
其他回答
$('input').focus(function () {
var self = $(this);
setTimeout(function () {
self.select();
}, 1);
});
编辑:根据@DavidG的请求,我不能提供详细信息,因为我不确定为什么这样工作,但我相信这与向上或向下传播的焦点事件或任何它所做的事情有关,输入元素获得它所接收的焦点通知。设置timeout会给元素一点时间来意识到它已经这样做了。
$(document).ready(function() {
$("input[type=text]").focus().select();
});
这也适用于iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
我的解决方案是:
var mouseUp;
$(document).ready(function() {
$(inputSelector).focus(function() {
this.select();
})
.mousedown(function () {
if ($(this).is(":focus")) {
mouseUp = true;
}
else {
mouseUp = false;
}
})
.mouseup(function () {
return mouseUp;
});
});
因此,鼠标通常会工作,但不会在通过输入获得焦点后取消选择
我知道这里已经有很多答案了——但这一个到目前为止还没有找到;一个解决方案,也与ajax生成的内容:
$(function (){
$(document).on("focus", "input:text", function() {
$(this).select();
});
});