什么是香草JS或jQuery解决方案,将选择一个文本框的所有内容时,文本框接收焦点?
当前回答
HTML:
var textFiled = document.getElementById("text-filed"); 文本文件。addEventListener("focus", function() {this.select();}); 输入你的文本:<input type=" Text " id=" Text -filed" value="test with filed Text ">
使用JQuery:
$("#text-filed").focus(function() { $(this).select(); } );
使用React JS:
在各自的组成部分-
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
其他回答
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
这也适用于iOS:
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
jQuery不是JavaScript,在某些情况下JavaScript更容易使用。
看看这个例子:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
来源:CSS Tricks, MDN
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
通过加入一些函数调用,我可以稍微改进Zach的回答。这个答案的问题是它完全禁用了onMouseUp,从而阻止你在文本框中点击,一旦它有焦点。
这是我的代码:
<input type="text" onfocus="this.select()" onMouseUp="javascript:TextBoxMouseUp();" onMouseDown="javascript:TextBoxMouseDown();" />
<script type="text/javascript">
var doMouseUp = true;
function TextBoxMouseDown() {
doMouseUp = this == document.activeElement;
return doMouseUp;
}
function TextBoxMouseUp() {
if (doMouseUp)
{ return true; }
else {
doMouseUp = true;
return false;
}
}
</script>
这比扎克的回答略有进步。它在IE中工作得很完美,在Chrome中完全不能工作,在FireFox中则是交替成功(几乎每隔一次)。如果有人有一个想法,如何使它可靠地工作在FF或Chrome,请分享。
总之,我想我应该分享我所能做的让这一切更美好。