日期:2014-05-16  浏览次数:20397 次

关于js替换选中文字!!要兼容...求高手帮忙啊~~
比如现在有一个div 它的contenteditable="true" 也就是可编辑的div层

有一个按钮 比如为:B

当我在编辑过程中 选中某些文字时 点击这个B按钮 然后当前选中的字就变为粗体
也就是说将选中文字改为<b>选中文字</b>的html

或者将选中文字替换为选中文字 然后在我提交的时候将这些[]替换为<>也行

说简单点就是一个文本编辑器嘛

求教 如何替换选中的文本 要兼容主流浏览器的

------解决方案--------------------
这个比较难,用现成的编辑器吧,在网上找一个。
------解决方案--------------------
试下吧~~
HTML code
<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>

------解决方案--------------------
HTML code
<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>