比如现在有一个div 它的contenteditable="true" 也就是可编辑的div层有一个按钮 比如为:B当我在编辑过程中 选中某些文字时 点击这个B按钮  然后当前选中的字就变为粗体
也就是说将选中文字改为<b>选中文字</b>的html或者将选中文字替换为选中文字 然后在我提交的时候将这些[]替换为<>也行说简单点就是一个文本编辑器嘛求教 如何替换选中的文本  要兼容主流浏览器的

解决方案 »

  1.   

    试下吧~~
    <html>
    <body>
    <div id="aa">好啦 写完这个就休息了 GOOD NIGHT!<divp>
    <script language="javaScript">
    var div = document.getElementById("aa");
    div.onmouseup = function() {
    var userSelection;
    if (window.getSelection) {
    // 现代浏览器
    userSelection = window.getSelection();
    } else if (document.selection) {
    // IE浏览器 
    userSelection = document.selection.createRange();
    }

    userSelection.pasteHTML("<b>" + userSelection.text + "</b>");
    };
    </script>
    </body>
    </html>
      

  2.   

    <divp> 我咋写了个这个 呵呵 改下吧</div>  完美点 
      

  3.   

    <textarea style="width:200px;height:200px;border:1px solid #000" id="editor">
    321321321321312321
    </textarea>
    <input type="button" onclick="func()" value="改变"/>
    <script type="text/javascript">
    function func()
    {
       var e = document.getElementById("editor")
       if(document.selection){
          var range = document.selection.createRange();
          range.text = "["+range.text+"]";
        }
       if(document.getSelection)
       {
           var start = e.selectionStart;
           var end = e.selectionEnd;
           e.value = e.value.substr(0, start) +"["+ e.value.substring(start,end)+"]" +
       e.value.substring(end, e.value.length);
       }
    }
    </script>