2013-07-12 34 views
2

我有一個包含許多輸入/文本區域的表單,使用表單的管理員可以在文本中添加動態值,例如:page title =「Hi {name},welcome to {shop_name}」。在表單的底部,我有一個所有可用動態值的列表。jquery在點擊後獲取光標位置

問:我試圖做的是點擊列表中的一個值,它找到以前的焦點輸入並插入值。

更簡單的把我怎麼會this jsFiddle工作這個輸入=文本相同,它爲textarea?所以如果我在輸入字段中有光標,它會在那裏添加foo值而不是textarea。

HTML

<form action="" method="post">  
    <label for="name">Name:</label> 
    <input name="name" type="text" /> 

    <label for="message">Message:</label> 
    <textarea name="message">Lorem ipsum dolor sit amet, consectetur adipiscing elit. </textarea> 

    <input value="Submit" type="submit" />   
</form> 

<h3>Insert short code</h3> 
<ul class="inserts"> 
    <li><a href="#" data-foo="{foo_1}">Foo 1</a></li> 
    <li><a href="#" data-foo="{foo_2}">Foo 2</a></li> 
    <li><a href="#" data-foo="{foo_3}">Foo 3</a></li> 
    <li><a href="#" data-foo="{foo_4}">Foo 4</a></li> 
    <li><a href="#" data-foo="{foo_5}">Foo 5</a></li> 
</ul> 

JS

jQuery.fn.extend({ 
    insertAtCaret: function (myValue) { 
     return this.each(function (i) { 
      if (document.selection) { 
       //For browsers like Internet Explorer 
       this.focus(); 
       var sel = document.selection.createRange(); 
       sel.text = myValue; 
       this.focus(); 
      } else if (this.selectionStart || this.selectionStart == '0') { 
       //For browsers like Firefox and Webkit based 
       var startPos = this.selectionStart; 
       var endPos = this.selectionEnd; 
       var scrollTop = this.scrollTop; 
       this.value = this.value.substring(0, startPos) + myValue + this.value.substring(endPos, this.value.length); 
       this.focus(); 
       this.selectionStart = startPos + myValue.length; 
       this.selectionEnd = startPos + myValue.length; 
       this.scrollTop = scrollTop; 
      } else { 
       this.value += myValue; 
       this.focus(); 
      } 
     }); 
    } 
}); 

$(".inserts a").click(function (e) { 
    e.preventDefault(); 
    $('textarea').insertAtCaret(
     $(this).data("foo") 
    ); 
}); 

回答

1

一個簡單的方法是,將光標的最後位置存儲在輸入字段中的變量。當單擊一個按鈕時,您可以輕鬆地將值插入到所需的位置。足夠的思想食物? ;)

編輯: 要插入位置x的字符串,您可以使用此jQuery caret plugin或拆分位置x上的原始輸入內容,並添加之間的新內容。您可能還想看看this thread

我的解決辦法是以下幾點:

var pos = 0; 

$('yourField').on('click keypress', function() { 
    pos = $(this).caret().start 
}); 

// inside your click function you can use the following 
// $.fn.caretTo(index , [ offset ]) 
// to add input to a specific position 
+0

所以我會創建一個通用的部門所有':input' –

+0

@JohnMagnolia:見我的編輯。 –