我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("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());
});
其他回答
这里有一些不错的答案,@user2072367是我最喜欢的,但当你通过标签而不是通过点击关注时,它会产生意想不到的结果。(意想不到的结果:通过标签聚焦后正常选择文本,必须再点击一次)
这个小提琴修复了这个小错误,并额外将$(This)存储在一个变量中,以避免多余的DOM选择。点击这里查看详情!(:
在IE >中测试
$('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();
});
我认为情况是这样的:
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);
});
找到一个很棒的解决方案阅读这篇文章
$(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);
});
}
});
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>
这个版本适用于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/