document.selection.createRange()


document.selection.createRange()  

2009-12-25 14:07:35|  分類: Technical|字號 訂閱

 
 

最近看突然看到相關內容,准備收集一下跨瀏覽器的相關操作。

 

設置選中的狀態。

  1. function SelectRange(obj,begin,end)   
  2. {   
  3.     if(obj.createTextRange) {   
  4.         var rng = obj.createTextRange();   
  5.         rng.moveStart("character",-0);   
  6.         rng.moveEnd("character",-0);   
  7.         rng.collapse(true);   
  8.         rng.moveStart("character",begin);   
  9.         rng.moveEnd("character",end-begin);   
  10.         rng.select();   
  11.     }   
  12.     if(obj.setSelectionRange){             
  13.         obj.setSelectionRange(begin, end);   
  14.     }      
  15. }   

 

相關知識:

setSelectionRange

document.selection  IE/Opera支持 Firefox/Safari/Chrome不支持

createRange()  IE/Opera支持 Firefox/Safari/Chrome不支持

createTextRange()  IE支持 Firefox/Safari/Chrome/Opera不支持

window.getSelection()  Firefox/Safari/Chrome/Opera支持 IE不支持

 

<style>
h2{color:red;font-family:Arial;background:#990000;padding:5px;color:#fff;  }
</style>
<body>
<div>123
    <p>456
         <span>789
                <b>bbbbb</b>
         </span>
    </p>
</div>
<hr/>
<button onclick="getParent()">察看選中的路徑</button>
<h2 id="show">&nbsp;</h2>
</body>
<script>
function getParent(){
 var o,path = [];
 o = document.all? document.selection.createRange().parentElement(): window.getSelection().focusNode.parentNode;
 do{
  path.push(o.tagName);
  
 }while(o=o.parentNode,o&&o!==document.body)
 alert(path.reverse().join('->'))
};
</script>

 

function getSelectText()
{
if(isIE)
{
alert(frameDoc.selection.createRange().text);
}
else
{
alert(frameWin.getSelection().getRangeAt(0));
}
}

 

<script language="javascript"> 
var editor; 
editor = document.getElementById("HtmlEdit").contentWindow; 
//只需鍵入以下設定,iframe立刻變成編輯器。 
editor.document.designMode = 'On'; 
editor.document.contentEditable = true; 
//但是IE與FireFox有點不同,為了兼容FireFox,所以必須創建一個新的document。 
editor.document.open(); 
editor.document.writeln('<html><body></body></html>'); 
editor.document.close(); 
//字體特效 - 加粗方法一 
function addBold() 

editor.focus(); 
//所有字體特效只是使用execComman()就能完成。 
editor.document.execCommand("Bold", false, null); 

//字體特效 - 加粗方法二 
function addBold() 

editor.focus(); 
//獲得選取的焦點 
var sel = editor.document.selection.createRange(); 
insertHTML("<b>"+sel.text+"</b>"); 

function insertHTML(html) 

if (editor.document.selection.type.toLowerCase() != "none") 

editor.document.selection.clear() ; 

editor.document.selection.createRange().pasteHTML(html) ; 

</script> 

 摘自於:http://blog.163.com/wr_asdf/blog/static/42930451200911252735453/


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM