我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
当前回答
这个版本适用于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/
其他回答
这将完成工作,并避免您无法再通过鼠标选择部分文本的问题。
$("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");
}
});
找到一个很棒的解决方案阅读这篇文章
$(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>
我使用FF 16.0.2和jquery 1.8.3,所有的代码在答案不工作。 我使用这样的代码工作。
$("input[type=text]").focus().select();
或者你可以使用<input onclick="select()“>完美。