有好像是replace函数具体用法查一下msdn

解决方案 »

  1.   

    谢谢坏小子。
    不过我想知道的是选定文本的定位。
    因为在thisText中输入的文本可能会很多,而且可能会有相同的文本的情况,所以不能用replace的方法。我想知道是否有其他的方法来定位。我可能在选定的文本两边插入其他不同的标签。
      

  2.   

    我曾经用了这样一个函数来定位,但是由于数据元素太多,提交的时候经常会出现内存出错的问题而自动关闭浏览器。所以想问问看有没有其他方法解决。
    function storeCaret (textEl) {
    if (textEl.createTextRange) 
    textEl.caretPos = document.selection.createRange().duplicate();
    }<input type="text" name="thisText" size="20" ONSELECT="storeCaret(this);" ONCLICK="storeCaret(this);" ONKEYUP="storeCaret(this);">
      

  3.   

    <SCRIPT language="javascript">
    function change(object){
    var svalue=object.createTextRange().text
    var nlen=svalue.length
    var oRang=document.selection.createRange()
    var nlenselect=oRang.text.length
    var npos=oRang.moveStart("character",1000)
    var nstart =nlen -npos+1
    var nend=nstart+nlenselect
    oRang=document.selection.createRange()
    oRang.text="<B>" + oRang.text + "</B>"
    alert("选择第"+nstart+"到"+nend+"第个字符");
    }
    </SCRIPT>
    <FORM method="POST" name="thisForm">
    <INPUT type="text" name="thisText" size="20" onMouseUp="change(this)" > 
    </FORM>
      

  4.   

    谢谢xmlingo(xmlingo), 不知还有其它方法吗?
      

  5.   

    给你一个例子,你自己好好看看吧!!挺复杂的,看明白了告诉我哟!:)
    ========================================================================
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN"><HTML><HEAD><TITLE></TITLE>
    <META http-equiv=Content-Type content="text/html; charset=gb2312">
    <STYLE>
    SELECT {
    BACKGROUND: #eeeeff; FONT: 8pt verdana,arial,sans-serif
    }
    .toolbar {
    BORDER-RIGHT: black 1px solid; BORDER-TOP: black 1px solid; BACKGROUND: lightgrey; MARGIN-BOTTOM: 3pt; OVERFLOW: hidden; BORDER-LEFT: black 1px solid; BORDER-BOTTOM: black 1px solid; HEIGHT: 28px
    }
    .mode LABEL {
    FONT: bold 10pt verdana,geneva,arial,sans-serif
    }
    .mode .current {
    COLOR: darkgreen
    }
    .heading {
    BACKGROUND: lightgrey; COLOR: navy
    }
    </STYLE><SCRIPT>var bLoad=false,public_description=new Editorfunction Editor() {
    this.put_html=put_html;
    this.get_html=get_html;
    this.testHTML=testHTML
    this.bReady = false
    }function cleanupHTML() {
      bodyTags=idEdit.document.body.all, i
      for (i=bodyTags.tags("FONT").length-1;i >= 0;i--)
    if (bodyTags.tags("FONT")[i].style.backgroundColor="#ffffff") {
    bodyTags.tags("FONT")[i].style.backgroundColor=""
    if (bodyTags.tags("FONT")[i].outerHTML.substring(0,6)=="<FONT>")
    bodyTags.tags("FONT")[i].outerHTML=bodyTags.tags("FONT")[i].innerHTML
    }
    }function testHTML(bAllowHead,extras) {
      mW.click()
      var badStuff=new Array("IFRAME","SCRIPT","LAYER","ILAYER","OBJECT","APPLET","EMBED","FORM","INPUT","BUTTON","TEXTAREA"),headStuff=new Array("HTML","BODY","TITLE","BASE","LINK","META","STYLE"),hasStuff=new Array(),bodyTags=idEdit.document.body.all,i=0
      for (i=0;i<badStuff.length;i++)
        if (bodyTags.tags(badStuff[i]).length>0)
          hasStuff[hasStuff.length]=badStuff[i]
      if (!bAllowHead)
        for (i=0;i<headStuff.length;i++)
          if (bodyTags.tags(headStuff[i]).length>0)
            hasStuff[hasStuff.length]=headStuff[i]
      if (extras!=null)
        for (i=0;i<extras.length;i++) 
          if (bodyTags.tags(extras[i]).length>0)
            hasStuff[hasStuff.length]=extras[i]
      var str=""
      if (hasStuff.length>0) {
        str="Please remove the following HTML Tags from your message and resubmit:"
        for (i=0;i<hasStuff.length;i++)
           str+="\n "+hasStuff[i]
        str+= "\nRemember, when using HTML Mode you may need to escape \nthe brackets surrounding tags (< and >) with &lt; and &gt;"
        setTimeout("mH.click()",0)
      }
      return str
    }function get_html() {if (bMode) {
     cleanupHTML()
     return idEdit.document.body.innerHTML 
    }
    else 
    return idEdit.document.body.innerText;
    }
    function put_html(sVal) {
    if (bMode) 
    idEdit.document.body.innerHTML=sVal 
    else 
    idEdit.document.body.innerText=sVal
    }var sHeader="<BODY STYLE=\"font:10pt geneva,arial,sans-serif\">",bMode=true,sel=nullfunction displayError() {alert("Formatting toolbar is only accessible in WYSIWYG mode");idEdit.focus()}function format(what,opt) {
     if (!bMode) {
       displayError()
       return
     }
     if (opt=="removeFormat"){
       what=opt;opt=null
     }
     if (opt=="CustomFont")
    opt = prompt("Format your text with what font face?","Geneva, Arial, Sans-Serif")
     if ((opt=="") && (what=="forecolor"))
    opt = prompt("Format your text with what color?","Black")
     if (bMode) {
       if (opt==null)
         idEdit.document.execCommand(what)
       else
         idEdit.document.execCommand(what,"",opt)
       var s=idEdit.document.selection.createRange(),p=s.parentElement()  
       idEdit.focus()
     } 
     sel=null
    }function getEl(sTag,start) {
      while ((start!=null) && (start.tagName!=sTag))
        start = start.parentElement
      return start
    }function createLink() {
     if (!bMode) {
       displayError()
       return
     }
     var isA = getEl("A",idEdit.document.selection.createRange().parentElement())
     var str=prompt("Where do you want to link to? (eg., http:\/\/www.SiteExperts.com\/)",isA ? isA.href : "http:\/\/")
     if ((str!=null) && (str!="http://")) {
       if ((idEdit.document.selection.type=="None") && (!isA)) {
         var sel=idEdit.document.selection.createRange()
         sel.pasteHTML("<A HREF=\""+str+"\">"+str+"</A> ")
         sel.select()
       }
       else
         format("CreateLink",str)
     }
     else
       idEdit.focus()
    }function setMode(bNewMode) {
     if (bNewMode!=bMode) {
      if (bNewMode) {
       var sContents=idEdit.document.body.innerText 
       idEdit.document.open()
       idEdit.document.write(sHeader)
       idEdit.document.close()
       idEdit.document.body.innerHTML=sContents
      }
      else {
       cleanupHTML()
       var sContents=idEdit.document.body.innerHTML
       idEdit.document.open()
       idEdit.document.write("<BODY style=\"font:10pt courier, monospace\">")
       idEdit.document.close()
       idEdit.document.body.innerText=sContents
      }
      bMode=bNewMode
      for (var i=0;i<htmlOnly.children.length;i++)
       htmlOnly.children[i].disabled=(!bMode)
     }
     modeA.className=bMode?"current":"";modeB.className=bMode?"":"current"
     idEdit.focus()
    }
    </SCRIPT><SCRIPT event=DocumentComplete() for=EditCtrl>
    /*if (!bLoad) {
    setTimeout("initEditor(true)",0)
    idBox.style.visibility=''
    idBox.focus()
    }*/
    bLoad=true
    </SCRIPT></HEAD>
    <BODY onselectstart="return false" 
    style="PADDING-RIGHT: 2pt; PADDING-LEFT: 2pt; PADDING-BOTTOM: 2pt; MARGIN: 0pt; CURSOR: default; PADDING-TOP: 2pt" 
    onload=doLoad()>
    <DIV id=idBox style="VISIBILITY: hidden; WIDTH: 100%; TEXT-ALIGN: center">
    <TABLE class=toolbar id=tb1 style="MARGIN-BOTTOM: 2pt; PADDING-TOP: 1pt" 
    cellSpacing=2 cellPadding=0>
      <TBODY>
      <TR>
        <TD id=htmlOnly vAlign=center noWrap><SELECT 
          onchange="format('formatBlock',this[this.selectedIndex].value);this.selectedIndex=0"> 
            <OPTION class=heading selected>Paragraph<OPTION value="<P>">Normal 
            &lt;P&gt;<OPTION value="<H1>">Heading 1 &lt;H1&gt;<OPTION 
            value="<H2>">Heading 2 &lt;H2&gt;<OPTION value="<H3>">Heading 3 
            &lt;H3&gt;<OPTION value="<H4>">Heading 4 &lt;H4&gt;<OPTION 
            value="<H5>">Heading 5 &lt;H5&gt;<OPTION value="<H6>">Heading 6 
            &lt;H6&gt;<OPTION value="<PRE>">Pre &lt;PRE&gt;<OPTION 
            style="COLOR: darkred" value=removeFormat>Clear 
          Formatting</OPTION></SELECT>&nbsp;&nbsp; <SELECT 
          onchange="format('fontname',this[this.selectedIndex].value);this.selectedIndex=0"> 
            <OPTION class=heading selected>Font<OPTION 
            value=geneva,arial,sans-serif>Arial<OPTION 
            value=verdana,geneva,arial,sans-serif>Verdana<OPTION 
            value=times,serif>Times<OPTION value="courier, monospace">Courier<OPTION 
            style="COLOR: navy" value=CustomFont>Custom...</OPTION></SELECT> <SELECT 
          onchange="format('fontSize',this[this.selectedIndex].text);this.selectedIndex=0"> 
            <OPTION class=heading 
            selected>Size<OPTION>1<OPTION>2<OPTION>3<OPTION>4<OPTION>5<OPTION>6<OPTION>7</OPTION></SELECT> 
          <SELECT 
          onchange="format('forecolor',this[this.selectedIndex].style.color);this.selectedIndex=0"> 
            <OPTION class=heading selected>Color<OPTION 
            style="COLOR: black">Black<OPTION style="COLOR: gray">Gray<OPTION 
            style="COLOR: darkred">Dark Red<OPTION style="COLOR: navy">Navy<OPTION 
            style="COLOR: darkgreen">Dark Green<OPTION>Custom...</OPTION></SELECT> 
      </TD></TR></TBODY></TABLE>
    <DIV class=toolbar onselectstart="return false" id=tb2 
    ondragstart="return false" style="WIDTH: 270px">
    <SCRIPT event="ShowContextMenu(xPos, yPos)" for=EditCtrl>//important</SCRIPT><SCRIPT>
    var buttons=new Array(24,23,23,4,23,23,23,4,23,23,23,23,4,24),action=new Array("bold","italic","underline","","justifyleft","justifycenter","justifyright","","insertorderedlist","insertunorderedlist","outdent","indent","","createLink"),tooltip=new Array("Bold Text","Italic Text","Underline Text","","Left Justify","Center Justify","Right Justify","","Ordered List","Unordered List","Remove Indent","Indent","","Create Hyperlink"),left=0,s=""
    for (var i=0;i<buttons.length;i++) {
     s+="<SPAN STYLE='position:relative;height:26;width: " + buttons[i] + "'><SPAN STYLE='position:absolute;margin:0px;padding:0;height:26;top:0;left:0;width:" + (buttons[i]) + ";clip:rect(0 "+buttons[i]+" 25 "+0+");overflow:hidden'><IMG BORDER=0 SRC='toolbar.gif' STYLE='position:absolute;top:0;left:-" + left + "' WIDTH=267 HEIGHT=50"
     if (buttons[i]!=4) {
       s+=" onmouseover='this.style.top=-25' onmouseout='this.style.top=0' ONCLICK=\""
       if (action[i]!="createLink") 
         s+="format('" + action[i] + "');this.style.top=0\" "
       else
       s+="createLink();this.style.top=0\" "
       s+="TITLE=\"" + tooltip[i] + "\""
     }
     s+="></SPAN></SPAN>"
     left+=buttons[i] 
    }
    document.write(s + "</DIV>")function initEditor(bWhichEditor) {
            // IE5 Secret Sauce
    if (bWhichEditor)
                    idEdit = EditCtrl.DOM.parentWindow 
    else {
    EditCtrl.document.designMode="On"
    idEdit = EditCtrl
    }
    idEdit.document.open()
            idEdit.document.write(sHeader)
    idEdit.document.close()
    // if (external.raiseEvent)
    // external.raiseEvent("onready",window.event)
    }function doLoad() {
    idBox.style.visibility=''
    // if (!(navigator.userAgent.indexOf("MSIE 5")>0)) {
    initEditor(false)
    bLoad=true;
    idEdit.focus()
    // }
    }//if (navigator.userAgent.indexOf("MSIE 5")>0) {
    // document.write("<OBJECT WIDTH=100% classid=\"clsid:2D360201-FFF5-11d1-8D03-00A0C959BC0A\" ID=EditCtrl></OBJECT>")
    //}
    //else {
    document.write("<IFRAME NAME=EditCtrl WIDTH=100%></IFRAME>")
    //}
    </SCRIPT><DIV class=mode id=tb3><NOBR><INPUT id=mW onclick=setMode(true) type=radio 
    CHECKED name=rMode><LABEL class=current id=modeA for=mw>WYSIWYG Mode</LABEL> 
    <INPUT id=mH onclick=setMode(false) type=radio name=rMode><LABEL id=modeB 
    for=mH>HTML Text Mode</LABEL></NOBR></DIV></DIV>
    <SCRIPT>
    setTimeout("document.all.EditCtrl.style.height=document.body.offsetHeight-90",0)
    window.onresize = new Function("document.all.EditCtrl.style.height=document.body.offsetHeight-90")
    </SCRIPT>
    </DIV>
    </BODY>
    </HTML>
      

  6.   

    虽然和你的问题不完全一样,可能会有启发!Have a Good Luck!!
      

  7.   

    谢谢net_lover(孟子E章) , 我看完再跟你聊聊。
      

  8.   

    to net_lover(孟子E章) : 你的这种方法是使用IFRAME的形式, 并不适合我的程序。因为我的程序中需要控制的对象太多了,而且会用JavaScript来生成很多的对象,所以不能对每一个对象都使用IFRAME的形式。无论如何都要谢谢你的帮助。如果还有什么好的方法一定要告诉我。谢了。以前在“榕树下”的论坛中也有你的这种使用IFRAME 来控制文本的方法。但是思路要清晰一点。有兴趣的话你可以去看看。或者我也可以发给你。
      

  9.   

    我的目的是想让你从中看出点什么,不知道不采用iframe能否实现!上面的代码太复杂了,说实在的,我都懒的看!!!所以我把所有的代码都发出来了!!里面可能有许多是不必要的代码。
      

  10.   

    不知道你是否用过花无缺的lb5000
    你将它解压后,在non-cgi/edior下的就是一个完整的文本编辑器。
    功能超酷www.17do.com
      

  11.   

    to polygame(polygame) :lb5000的编辑器和榕树下的是一模一样的,也是使用iframe格式。
    不过也要谢谢你的帮助。
      

  12.   

    <HTML>
    <HEAD>
         <SCRIPT>
         function storeCaret (textEl) {
           if (textEl.createTextRange) 
             textEl.caretPos = document.selection.createRange().duplicate();
             aForm.aText.value=textEl.caretPos.text
         }
         function insertAtCaret (textEl,text) {
           if (textEl.createTextRange && textEl.caretPos) {
             var caretPos = textEl.caretPos;
             caretPos.text =
               caretPos.text.charAt(caretPos.text.length - 1) == ' ' ?
                 text + ' ' : text;
           }
           else
             textEl.value  = text;
         }
         </SCRIPT>
    </HEAD>
    <BODY>
         <FORM NAME="aForm">
         <TEXTAREA NAME="aTextArea" ROWS="5" COLS="80" WRAP="soft" ONSELECT="storeCaret(this);">     【孟宪会之精彩世界】的例子!
         http://lucky.myrice.com
         </TEXTAREA>
         <BR>
         <INPUT TYPE="text" NAME="aText" SIZE="80">
         <BR>
         <INPUT TYPE="button" VALUE="在光标处插入文字" ONCLICK="insertAtCaret(this.form.aTextArea,'<b>'+aForm.aText.value+'</b>');">
         </FORM>
    </BODY>
    </HTML>
      

  13.   

    to:net_lover(孟子E章) 
    有沒有圖片 toolbar.gif 小弟感激不盡!!!