2010-08-09 71 views

回答

2

我覺得沒有內置函數來獲取選擇代碼的開始和結束位置。你需要編寫一些JS編碼來獲得這些位置。我寫過簡單的編碼。我不確定它是否有用。但是,檢查出來。

<html> 
    <head> 
     <script> 
      function GetSelectedText() 
      { 
       var fullString = "I feel there is no built-in functions for getting start and end position of selection code. you need to write some JS coding for getting these position. I've wrote just simple coding. I'm not sure whether it will be useful or not. But, check it out."; 
       if (window.getSelection) 
        {    
         var range = window.getSelection();      
         var startPosition = fullString.search(range); 
         var getPosition = range.toString(); 
         var endPosition = parseInt(getPosition.length) + parseInt(startPosition) 
         alert ("Start position : " + startPosition + " and End position : " + endPosition);   
        } 
       else 
        { 
         if (document.selection.createRange) 
         { 
          var range = document.selection.createRange(); 
          var startPosition = fullString.search(range.text); 
          var getPosition = range.text; 
          var endPosition = parseInt(getPosition.length) + parseInt(startPosition); 
          alert ("Start position : " + startPosition + " and End position : " + endPosition); 
         } 
        }  
      } 
     </script> 
    </head> 
    <body> 
     <button onclick="GetSelectedText()"> 
      Get 
     </button> 
     I feel there is no built-in functions for getting start and end position of selection code. you need to write some JS coding for getting these position. I've wrote just simple coding. I'm not sure whether it will be useful or not. But, check it out. 
    </body> 
</html> 

對於這種編碼,你需要在兩個地方定義你的短信。一種是在JS編碼中

var fullString =「??」

,另一個是車身的消息按鈕下的/

+0

我得到0的開始和結束位置 – Rana 2010-08-09 20:30:58

+0

對不起。我修復了一些錯誤並編輯了上面的代碼。鄧忘記遵循我的指示。 – ppshein 2010-08-10 02:12:08

+0

這是一個好的開始。 – Rana 2010-08-22 05:38:34

0

我認爲較短的方法是使用JavaScript的string.indexOf()函數。它只是在較大的字符串中返回搜索字符串的起始索引,如果不存在則返回-1。結束索引可以通過將起始索引添加子字符串的長度來計算。

+0

重複文字怎麼樣?如果用戶選擇「the」,indexOf的第一次出現可能不是選定的單詞? – Rana 2010-08-09 20:30:33