开发者

Cursor position, jquery

From this post I found and answer on how to position the cursor in a textarea.

I am creating a jquery chat and I wanted to create a simple html textarea, having a div infront of the textarea displying the html contained in the textarea.

Mark posted the following script:

$.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);
                        rang开发者_运维知识库e.select();
                }
        });
};

Witch works fine, but my problem is, how do I find the end position in the div of the html displayed there?


If by showing the HTML contained in the textarea you mean your chat can contain tags like <img> and <a>, you need to escape the tags. I'm guessing that is what you want, so try this:

HTML (for reference)

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

Script

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

*Note: you could replace keyup with keydown or keypress but I find the it works better with keyup.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜