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

js的selection问题
我要自己写个富文本编辑器,要求不能用iframe,用div contenteditable置为true,这样document.selection就不能唯一锁定div里面的内容了,那些加粗,变斜的操作就对整个document的selection都起作用了,怎么样才能让这些操作只操作div里面被选中的文本,望高手指教

------解决方案--------------------
google baidu
------解决方案--------------------
HTML code
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
 <HEAD>
  <TITLE> Demo for DIV editor </TITLE>
  <META NAME="Author" CONTENT="Anbert">
 </HEAD>

 <BODY>
    <SCRIPT LANGUAGE="JavaScript">
    <!--
        function Exec(sCmd){        
            var cmd = "",bUserInterface = false,vValue = 0;
            
            switch(sCmd){
                case 'b':
                    cmd = "Bold";
                    break;
                case 'i':
                    cmd = "Italic";
                    break;
                case 's':
                    cmd = "FontSize";
                    vValue = getFontSize(); 
                    break;
                case 'c':
                    cmd = "ForeColor";
                    vValue = getFontColor();
                    break;
                //more........
            }
            document.selection.createRange().execCommand(cmd,bUserInterface,vValue);        
        }
        function execute(cmd){
            document.selection.createRange().execCommand(cmd);
        }
        function getFontSize(){
            return font_size.options[font_size.selectedIndex].value;
        }
        function getFontColor(){
            //it's not a real color,just show how to use the command;
            return "#" + fcolor.style.backgroundColor.toString(16);
        }
        function forecolor(){            
            CDC.ShowColor();        
            var c = CDC.Color;
            var obj = fcolor;
            obj.style.backgroundColor=c;        
            Exec('c');
        }
    //-->
    </SCRIPT>

<BR>

   <button  onclick="Exec('b')"> 粗体 </button> <button  onclick="Exec('i')"> 斜体 </button> 
   <select onchange="Exec('s')" id=font_size><option value=1>一号</option><option value=2>二号</option><option value=3>三号</option><option value=4>四号</option><option value=5>五号</option><option value=6>六号</option><option value=7>七号</option></select>   
   <button id="fcolor" style="width:40;background:black;cursor:hand;" onclick="forecolor();"></button>

   <br /><br />

   <div style="border:solid 1px blue;width:100%;height:300;" contentEditable="true" id="titi">
    test   </div>

   <form target="_blank" action = "http://www.baidu.com/s" ><input type="hidden" id="wd" name="wd"><input type="submit" onclick="wd.value=titi.innerHTML"></form>

   <OBJECT ID="CDC" CLASSID="CLSID:F9043C85-F6F2-101A-A3C9-08002B2F49FB"></OBJECT>
 </BODY>
</HTML>