javascript 선택 영역 selection 의 텍스트 교체 및 삽입 방식

2005 단어 domrange
질문http://blog.csdn.net/pgmsoul/article/details/8306899)
//        ,  text       
function repaceSelectionText(text) {
    // IE   
    if (window.getSelection) {
        var sel = window.getSelection();
        alert(sel.rangeCount); //    ,     1 .
        sel.deleteFromDocument(); //       
        var r = sel.getRangeAt(0); //       deleteFromDocument(),               .
        var selFrag = r.cloneContents(); //       
        var frag = selFrag.childNodes; //     deleteFromDocument(),           0 
        for (var i = 0; i < frag.length; i++) {
            alert(frag[i].nodeName); //       
        }
        var h1 = document.createElement('H1'); //        
        h1.innerHTML = text; //         
        r.insertNode(h1); //        ,              ,           ,                ,     deleteFromDocument()  .
    }
    else if (document.selection && document.selection.createRange) {
        //IE   
        var sel = document.selection.createRange(); //      
        alert(sel.htmlText); //    html  .
        sel.pasteHTML('<h1>  </h1>'); //      html  ,         .
    }
}

2. 텍스트 삽입
 function insertSelectionText(html)
{
  if(document.selection && document.selection.createRange)
  {
          /****      IE         ,       **************/
          document.selection.createRange().pasteHTML(html);
        }else{
          var selection = document.getSelection();
          var range;
          if (selection)
           {
            range = selection.getRangeAt(0);
          }else {
            range = iframeDocument.createRange();
          }
          var oFragment = range.createContextualFragment(html),
          oLastNode = oFragment.lastChild ;
          range.insertNode(oFragment) ;
          range.setEndAfter(oLastNode ) ;
          range.setStartAfter(oLastNode );
          selection.removeAllRanges();//    
          selection.addRange(range);

        }
        
 }

좋은 웹페이지 즐겨찾기