2010-08-09 69 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