天天看點

document.getSelection,document.selection.createRange

<script>

function getSel()

{

      var txt = '';

      var foundIn = '';

      if(window.getSelection)

      {

          txt = window.getSelection();

          foundIn = 'window.getSelection()';

      }else if(document.getSelection)

      {

          txt = document.getSelection();

          foundIn = 'document.getSelection()';

      }else if(document.selection)

      {

          txt = document.selection.createRange().text;

          foundIn = 'document.selection.createRange()';

      }else

          return;

      document.forms[0].selectedtext.value = 'Found in: ' + foundIn + '/n' + txt;

}

</script>

<form>

<textarea name="selectedtext" rows="5" cols="50">

</textarea><br>

<input type="button" value="Getselection" οnmοusedοwn="getSel()">

</form>

以上的代碼可以捕獲到選中的網頁中的純文字内容(不含HTML标簽)

如果想獲得包含html的内容,将document.selection.createRange().text改成document.selection.createRange().htmlText  

IE:document.selection   FireFox:window.getSelection()   document.selection隻有IE支援,window.getSelection()也隻有FireFox和   Safari支援,都不是标準文法。

selection   對象

代表了目前激活選中區,即高亮文本塊,和/或文檔中使用者可執行某些操作的其它元素。

selection   對象的典型用途是作為使用者的輸入,以便識别正在對文檔的哪一部分正在處理,或者作為某一操作的結果輸出給使用者。

使用者和腳本都可以建立選中區。使用者建立選中區的辦法是拖曳文檔的一部分。腳本建立選中區的辦法是在文本區域或類似對象上調用   select   方法。要擷取目前選中區,請對   document   對象應用   selection   關鍵字。要對選中區執行操作,請先用   createRange   方法從選中區建立一個文本區域對象。

一個文檔同一時間隻能有一個選中區。選中區的類型決定了其中為空或者包含文本和/或元素塊。盡管空的選中區不包含任何内容,你仍然可以用它作為文檔中的位置标志。