簡體   English   中英

在單擊時在文本字段中選擇文本?

[英]select the text in a text field when clicked?

當用戶單擊文本輸入字段時,如何選擇文本字段中的文本?

我用過這段代碼:

  $("input[type=text]").focus(function() {
      $(this).select();
  });

但它在野生動物園中不起作用。 在FF中有時會起作用。

jQuery中的select()方法僅觸發所有匹配對象的select事件。 如果要操縱文本框中選定的文本范圍,則需要做一些更奇特的事情。 現代瀏覽器在這里的行為有所不同。

以下代碼應在Chrome,Firefox,IE,Safari和Opera中運行:

<input type="text" id="textBox" />
<script type="text/javascript">
$(document).ready(function(){
    function textBox_click(ev) {
        if (this.createTextRange) {
            // This is for IE and Opera.
            range = this.createTextRange();
            range.moveEnd('character', this.value.length);
            range.select();
        } else if (this.setSelectionRange) {
            // This is for Mozilla and WebKit.
            this.setSelectionRange(0, this.value.length);
        }
    }

    $('#textBox').click(textBox_click);
});
</script>

嘗試:

$("input[type=text]").focus().select();

這在Opera,FF,IE中對我有用

$("input[type=text]").focus(function() {
    this.select();
});

我只是在HTML中使用它:

... onclick="this.select()" 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM