2011-01-09 22 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