简体   繁体   English

在单击时在文本字段中选择文本?

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

how can you so that the text in the text field is selected when the user clicks on the text input field? 当用户单击文本输入字段时,如何选择文本字段中的文本?

i have used this code: 我用过这段代码:

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

but it doesnt work in safari. 但它在野生动物园中不起作用。 and in FF it works sometimes. 在FF中有时会起作用。

The select() method in jQuery simply triggers the select event on all matched objects. jQuery中的select()方法仅触发所有匹配对象的select事件。 You need to do something fancier if you want to manipulate the selected range of text in a textbox. 如果要操纵文本框中选定的文本范围,则需要做一些更奇特的事情。 Modern browsers behave differently here. 现代浏览器在这里的行为有所不同。

The following code should work in Chrome, Firefox, IE, Safari, and Opera: 以下代码应在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();

This works for me in Opera, FF, IE 这在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