我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
当前回答
与原生JavaScript select()一起工作很好。
$("input[type=text]").focus(function(event) {
event.currentTarget.select();
});
或者概括地说:
$("input[type=text]")[0].select()
其他回答
我认为这是更好的解决办法。不像在onclick事件中简单地选择,它不阻止用鼠标选择/编辑文本。它适用于包括IE8在内的主要渲染引擎。
$('input').on('focus', function (e) {
$(this)
.one('mouseup', function () {
$(this).select();
return false;
})
.select();
});
http://jsfiddle.net/25Mab/9/
var timeOutSelect;
$("input[type=text]").focus(function() {
var save_this = $(this);
clearTimeout(timeOutSelect);
timeOutSelect = window.setTimeout (function(){
save_this.select();
}, 100);
});
如果您在两个输入之间快速切换,请使用clearTimeout来获得更多的安全性。 清除旧的超时…
这里有一些不错的答案,@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();
});
试着用点击代替聚焦。它似乎对鼠标和键事件都有效(至少在Chrome/Mac上):
jQuery < 1.7版本:
$("input[type='text']").click(function () {
$(this).select();
});
jQuery 1.7+版本:
$("input[type='text']").on("click", function () {
$(this).select();
});
这是一个演示
我使用FF 16.0.2和jquery 1.8.3,所有的代码在答案不工作。 我使用这样的代码工作。
$("input[type=text]").focus().select();