如何使用简单的原生JavaScript或jQuery实现在文本框获得焦点时全选文本框中的内容?
如何使用简单的原生JavaScript或jQuery实现在文本框获得焦点时全选文本框中的内容?
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />
onmouseup="return false;"
。并且纯JavaScript加1! - clabe45$(document).ready(function() {
$("input[type=text]").focus().select();
});
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
mouseup
事件默认行为的一个缺点:“一旦光标在字段中,点击所选文本内的某个位置将光标定位到那里就无法工作;点击被有效地禁用。尽管如此,在需要在焦点上选择整个文本的情况下,这可能是两害相权取其轻的选择。” - JohnKjQuery不是JavaScript,某些情况下使用起来更加容易。
看这个例子:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
来源:CSS Tricks,MDN
HTML:
var textFiled = document.getElementById("text-filed");
textFiled.addEventListener("focus", function() { this.select(); });
Enter Your Text : <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()}
/>
onFocus={(e) => e.target.select()}
- Paito这不仅是Chrome/Safari的问题,我在Firefox 18.0.1上也遇到了类似的情况。有趣的是这在MSIE上并没有发生!问题出在第一个mouseup事件,它强制取消选择输入内容,所以忽略第一次出现的事件即可。
$(':text').focus(function(){
$(this).one('mouseup', function(event){
event.preventDefault();
}).select();
});
timeOut方法会导致奇怪的行为,阻止了每一个mouseup事件,你无法通过再次点击输入元素来取消选择。
我的解决方案是使用超时。看起来还可以正常工作。
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
<input type="text" onclick="this.focus(); this.setSelectionRange(0, 9999);" />
https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/select
我知道内联代码不是一个好的风格,但我不想将这个放入.js文件中。 不需要使用jQuery!
<input type="text" value="blah blah" onfocus="this.select(); this.selAll=1;" onmouseup="if(this.selAll==0) return true; this.selAll=0; return false;"></input>