开发者

On focus, do customized focus on textarea

开发者 https://www.devze.com 2023-02-03 11:46 出处:网络
My Code: $(\'#myTextArea\').one(\'focus\', function() { $(\'#myTextArea\')[0].selectionStart = 2; $(\'#myTextArea\')[0].selectionEnd = 6;

My Code:

$('#myTextArea').one('focus', function() {
     $('#myTextArea')[0].selectionStart = 2;
     $('#myTextArea')[0].selectionEnd = 6;
     $('#myTextArea')[0].focus();
});

The code works fine, on focus (only once), it selects from index 2 to 6.

The problem: since this function is called on focus, it does the custom focus, but then it calls focus AGAIN and I lose focus of the selected text. Any po开发者_运维百科ssible solution?


I'm not exactly sure why this works but I think it might just do the trick:

$('#myTextArea').bind("focus mousedown", "click", function(event) {
    event.preventDefault();
    $(this).select();
    this.selectionStart = 2;
    this.selectionEnd = 6;
});

Try it here.


Since you're already binding to the focus event and you aren't preventing the default behavior, you shouldn't need to fire .focus() manually. Try this instead:

$('#myTextArea').one('focus', function(event) {
     event.preventDefault();
     this.selectionStart = 2;
     this.selectionEnd = 6;
});
0

精彩评论

暂无评论...
验证码 换一张
取 消