什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
我有点晚了,但这在IE11, Chrome, Firefox中工作完美,没有混乱的鼠标(没有JQuery)。
inputElement.addEventListener("focus", function (e) {
var target = e.currentTarget;
if (target) {
target.select();
target.addEventListener("mouseup", function _tempoMouseUp(event) {
event.preventDefault();
target.removeEventListener("mouseup", _tempoMouseUp);
});
}
});
其他回答
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
<输入类型=“文本”
什么是JavaScript或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
您只需要添加以下属性:
onfocus="this.select()"
例如:
<input type="text" value="sometext" onfocus="this.select()">
(说实话,我不知道你为什么还需要其他东西。)
$(document).ready(function() {
$("input[type=text]").focus().select();
});
我的解决方案是:
var mouseUp;
$(document).ready(function() {
$(inputSelector).focus(function() {
this.select();
})
.mousedown(function () {
if ($(this).is(":focus")) {
mouseUp = true;
}
else {
mouseUp = false;
}
})
.mouseup(function () {
return mouseUp;
});
});
因此,鼠标通常会工作,但不会在通过输入获得焦点后取消选择