2011-01-09 47 views
1

我的代码:专注,做定制的重点textarea的

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

的代码工作正常,焦点(仅一次),它从指数选择2至6

的问题:因为这函数在焦点上调用,它执行自定义焦点,但随后它会调用焦点并重新获得所选文本的焦点。任何可能的解

+0

尝试定义对焦功能为空?这可能会起作用。就像$(“#myTextArea”)。focus(function(){}); – codersarepeople 2011-01-09 08:28:46

+0

这没有帮助:( – evilReiko 2011-01-09 08:39:07

回答

2

我也不清楚为什么这个工作,但我认为这可能只是做的伎俩:

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

Try it here.

1

由于您已经绑定到focus事件,并且您没有阻止默认行为,所以您不需要手动激发.focus()。试试这个:

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

它执行自定义焦点,但它会自动立即执行默认焦点,导致textarea失去我的自定义焦点。有没有办法阻止默认焦点? – evilReiko 2011-01-09 08:43:13