开发者

Build textarea with formatting controls - how to get selected text

开发者 https://www.devze.com 2023-03-08 22:30 出处:网络
Just for fun, I want to build simple text formatting tools for a textarea.To begin, I want to be able to enclose high-lighted text in a textarea with ** if it is to be in bold format (just like stacko

Just for fun, I want to build simple text formatting tools for a textarea. To begin, I want to be able to enclose high-lighted text in a textarea with ** if it is to be in bold format (just like stackoverflow's textarea editor). I've written the following code, which works most of the time, but it does have a bug, which I'll explain shortly.

<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
<script type="text/javascript" language="javascript">
var tmpText = '';
$(document).ready(function(){
        tmpText = '';
        $('#btn_bold').click(function(){bold(tmpText);});
        $('textarea').bind('mouseup', function(){
                  tmpText = '';
                  if(window.getSelection){
                    tmpText = window.getSelection().toString();
                  }else if(document.getSelection){
                    tmpText = document.getSelection().toString();
                  }else if(document.selection){
                    tmpText = document.selection.createRange().text;
                  }
        });
});

function bold(str)
{
        $('textarea').val($('textarea').val().replace(str,'**'+str+'**'));
}
</script>
</head>
<body>
<button type="button" id="btn_bold">bold it</button>
<textarea>AA</textarea>
</body>
</html>

So if you high-light the first letter A and bold it, you'll get the result **A**A. But if you high-light the second letter A and bold it, you still get **A**A, instead of A**A** because the line of code $('textarea').val($('textarea').val().replace(str,'**'+s开发者_如何学编程tr+'**')); is insufficient at identifying which letter A you want to bold.

What's an efficient way to identify high-lighted text and bold it?


I've written a jQuery plug-in that does this that I can extract out to a standalone script if it would help. An example of using the plugin to replace selected text with the word "hello".

<html>
<head>
<script type="text/javascript" language="javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"></script> 
<script type="text/javascript" language="javascript" src="http://rangyinputs.googlecode.com/files/textinputs_jquery.js"></script>
<script type="text/javascript" language="javascript">

$(document).ready(function() {

        $('textarea').bind('mouseup',function() { $(this).replaceSelectedText('hello');});
});
</script>
</head>
<body>
<textarea style="width:300px; height:300px;">
AAA
</textarea>
</body>
</html>

Also, as I commented in a related question of yours, the function you have there won't work for textareas, which have a separate mechanism for dealing with selections. See my answer there for a function that will work.


The selection object returns the string if you call tostring() on it. You can also get the range object, which has more information about the starting and ending points.

https://developer.mozilla.org/en/DOM/Selection

and

http://www.w3.org/TR/DOM-Level-2-Traversal-Range/ranges.html


As demonstrated here, you could do it like this:

el = document.getElementById('texty');
  if (el.setSelectionRange) {

     el.value = el.value.substring(0,el.selectionStart) + "**" + el.value.substring(el.selectionStart,el.selectionEnd) + "**" + el.value.substring(el.selectionEnd,el.value.length);

  }
  else if(document.selection.createRange()) {
      document.selection.createRange().text = "**" + document.selection.createRange().text + "**"; 
  }

However, note that this method is limited to textareas.


 <head>
 <script type="text/javascript">
    function formatText(el,tagstart,tagend) {
      if (el.setSelectionRange) {
        el.value = el.value.substring(0,el.selectionStart) + tagstart +
        el.value.substring(el.selectionStart,el.selectionEnd) + tagend +
        el.value.substring(el.selectionEnd,el.value.length)
      } else {
        // IE code 
        var selectedText = document.selection.createRange().text;
        var tag="b"
        if (selectedText != "") {
          var newText = "<" + tag + ">" + selectedText + "</" + tag + ">";
          document.selection.createRange().text = newText;
        }
      }
    }
</head>
<body>
  <p> <textarea rows="30" cols="59" name="Write-my-life-moments" 
       id="write-my-life- moments"></textarea> </p>

  <input type="button" value="BOLD"  
     onclick="formatText(document.getElementById('write-my-life-moments'), 
     '<b>','</b>')" />
</body>

This Code Works For FF, IE(6)> , Opera 9>, Safari. I Tested It On these Browsers. not on Old ones. So please Check this on old browsers. i dont get time to check it on old browsers (It Does not show my text area opening tag y? i don't know, so please dd yourself. write-my-life-moments. it is name of text area) `

0

精彩评论

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