我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
我使用这段代码尝试在用户聚焦于字段时选择字段中的所有文本。发生的事情是,它选择了所有的一秒钟,然后它被取消选择,输入光标留在我点击的地方…
$("input[type=text]").focus(function() {
$(this).select();
});
我希望一切都能被选中。
当前回答
var timeOutSelect;
$("input[type=text]").focus(function() {
var save_this = $(this);
clearTimeout(timeOutSelect);
timeOutSelect = window.setTimeout (function(){
save_this.select();
}, 100);
});
如果您在两个输入之间快速切换,请使用clearTimeout来获得更多的安全性。 清除旧的超时…
其他回答
这将完成工作,并避免您无法再通过鼠标选择部分文本的问题。
$("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");
}
});
<script>$.ready( $("input[type=text]").attr("onclick" , "this.select()"));<script>
我认为这是更好的解决办法。不像在onclick事件中简单地选择,它不阻止用鼠标选择/编辑文本。它适用于包括IE8在内的主要渲染引擎。
$('input').on('focus', function (e) {
$(this)
.one('mouseup', function () {
$(this).select();
return false;
})
.select();
});
http://jsfiddle.net/25Mab/9/
我来自2016年底,这段代码只适用于最新版本的jquery (jquery-2.1.3.js在这种情况下)。
if ($(element).is("input")) {
$(element).focus(function () {
$(element).select();
});
}
var timeOutSelect;
$("input[type=text]").focus(function() {
var save_this = $(this);
clearTimeout(timeOutSelect);
timeOutSelect = window.setTimeout (function(){
save_this.select();
}, 100);
});
如果您在两个输入之间快速切换,请使用clearTimeout来获得更多的安全性。 清除旧的超时…