我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
当前回答
我总是使用requestAnimationFrame()来跳过内部事件后机制,这在Firefox中工作完美。还没有在Chrome上测试过。
$("input[type=text]").on('focus', function() {
requestAnimationFrame(() => $(this).select());
});
其他回答
var timeOutSelect;
$("input[type=text]").focus(function() {
var save_this = $(this);
clearTimeout(timeOutSelect);
timeOutSelect = window.setTimeout (function(){
save_this.select();
}, 100);
});
如果您在两个输入之间快速切换,请使用clearTimeout来获得更多的安全性。 清除旧的超时…
我认为情况是这样的:
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);
});
我使用FF 16.0.2和jquery 1.8.3,所有的代码在答案不工作。 我使用这样的代码工作。
$("input[type=text]").focus().select();
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>
我总是使用requestAnimationFrame()来跳过内部事件后机制,这在Firefox中工作完美。还没有在Chrome上测试过。
$("input[type=text]").on('focus', function() {
requestAnimationFrame(() => $(this).select());
});