2009-10-25 175 views
0

this post我找到並回答瞭如何將光標放在textarea中。光標位置,jquery

我正在創建一個jQuery聊天,並且我想創建一個簡單的html textarea,並在textarea中顯示textarea中包含的html。

標誌貼在下面的腳本:

$.fn.selectRange = function(start, end) { 

     return this.each(function() { 
       if(this.setSelectionRange) { 
         this.focus(); 
         this.setSelectionRange(start, end); 
       } else if(this.createTextRange) { 
         var range = this.createTextRange(); 
         range.collapse(true); 
         range.moveEnd('character', end); 
         range.moveStart('character', start); 
         range.select(); 
       } 
     }); 
}; 

女巫工作正常,但我的問題是,我怎麼發現那裏顯示的HTML的DIV結束位置?

+0

我不明白這個問題。 「結束」是關於TEXTAREA的選擇,你明白嗎?那麼你想在textarea中選擇什麼? – Nickolay 2009-10-25 14:53:23

回答

0

如果通過顯示textarea中包含的HTML,表示您的聊天可以包含標籤,如<img><a>,則需要轉義標籤。我猜這就是你想要什麼,所以試試這個:

HTML(僅供參考)

<div id="formatted"></div> 
<textarea id="textchat"></textarea> 

腳本

$(document).ready(function(){ 
$('#textchat').keyup(function(){ 
    var txt = $(this).val(); 
    txt = txt.replace(/</g,'&lt;').replace(/>/g,'&gt;'); 
    $('#formatted').html(txt); 
}) 
}) 

*注意:你可以用​​或keypress但更換keyup我發現它與keyup效果更好。