javascript - 當文字框獲得焦點時選擇所有內容(Vanilla JS 或 jQuery)
有什麼 Vanilla JS 或 jQuery 的解決方案可以在文本框獲得焦點時選取文本框的所有內容?
答案#1
$(document).ready(function() {
$("input:text").focus(function() { $(this).select(); } );
});
答案#2
<input type="text" onfocus="this.select();" onmouseup="return false;" value="test" />答案#3
$(document).ready(function() {
$("input[type=text]").focus().select();
});
答案#4
$(document).ready(function() {
$("input:text")
.focus(function () { $(this).select(); } )
.mouseup(function (e) {e.preventDefault(); });
});
答案#5
jQuery 不是 JavaScript,但在某些情況下更容易使用。
看這個例子:
<textarea rows="10" cols="50" onclick="this.focus();this.select()">Text is here</textarea>
來源:CSS Tricks,MDN
答案#6
HTML :
document.getElementById("text-filled").addEventListener("focus", function() { this.select(); });Enter Your Text : <input type="text" id="text-filled" value="test with filled text">使用 JQuery :
$("#text-filled").focus(function() { $(this).select(); } );
使用 React JS :
在各自的組件中 -
<input
type="text"
value="test"
onFocus={e => e.target.select()}
/>
答案#7
這不只是 Chrome/Safari 的問題,我在 Firefox 18.0.1 也遇到了類似的情況。有趣的是,這在 MSIE 上並不會發生!這裡的問題是第一次 mouseup 事件會強制取消選取輸入內容,所以只需忽略第一次發生即可。
$(':text').focus(function(){
$(this).one('mouseup', function(event){
event.preventDefault();
}).select();
});
timeOut 方法會導致奇怪的行為,並且阻止每個 mouseup 事件,你無法透過再次點擊輸入元素來取消選取。
答案#8
我的解決方法是使用超時。似乎運作得不錯
$('input[type=text]').focus(function() {
var _this = this;
setTimeout(function() {
_this.select();
}, 10);
});
