2009-10-25 284 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效果更好。