简体   繁体   English

更改文本并在输入中设置光标

[英]Changing a text and setting a cursor in the input

I have an input that contains a text. 我有一个包含文本的输入。 When I click into this input, so the color of the text will change. 当我单击此输入时,文本的颜色将改变。 In the input is eg. 在输入是例如。 the text 'Hello buddy' - and when I click into the input in the end of the word Hello , so exist any easy way to set the cursor on the start (before the word Hello )? 文字“ Hello buddy”-当我在Hello单词的末尾单击输入时,是否存在任何将光标设置在开始位置的简单方法(在Hello单词之前)?

$('#your_name').focus(function(){
    if($(this).val() == $(this).attr('title')){
        $(this).css('color', 'red');
    }

    $(this).keyup(function() {
      $(this).val('');
    });
});

And when I start to type a text into the, how can I remove the current text Hello buddy and have in the input only the "new" text? 当我开始在中键入文本时,如何删除当前文本Hello buddy ,并在输入中仅包含“新”文本? I am trying to do with keyup method, but everything what I type is deleted. 我正在尝试使用keyup方法,但是我键入的所有内容都被删除了。

See my DEMO here. 在这里查看我的演示 Also modified your jsFiddle.. see here 还修改了您的jsFiddle ..参见此处

Edit : You can just use el.setSelectionRange(index, index); 编辑 :您可以只使用el.setSelectionRange(index, index); to set the caret position. 设置插入标记的位置。

And for your second question about removing the whole text when you keyup, You can use .one method which will executed only once., 对于第二个有关在键入键时删除整个文本的问题,可以使用.one方法,该方法仅执行一次。

$(this).one('keydown', function() {
      $(this).val('');
});

You can use the selectionStart property of an input field to get the location of the caret and you can then check if this is behind the word 'Hello', by matching with the value of the field. 您可以使用输入字段的selectionStart属性来获取插入符号的位置,然后可以通过与该字段的value匹配来检查它是否在单词“ Hello”之后。 You can then use setSelectionRange to set the caret to a position. 然后,您可以使用setSelectionRange将插入符号设置为一个位置。 setSelectionRange(0,0); will set it to the beginning. 将其设置为开始。

Edit: I just reread your questions and if you just want to delete all text when you type in it again, you can just use select() to select all text in the field. 编辑:我只是重新阅读了您的问题,如果您只想在再次输入时删除所有文本,则可以使用select()选择该字段中的所有文本。 If you then start typing it deletes the selected text. 如果您随后开始输入,它将删除所选文本。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM