获取选择文本的偏移量

时间:2013-12-04 14:19:06

标签: jquery html

我有像

这样的HTML代码
<div id="content">
   <span class="pivot">1</span>
   I know this is a really simple
   <span class="pivot">2</span>
   question
   <span class="pivot">3</span>
   to answer 
   <span class="pivot">4</span>
   please 
   <span class="pivot">5</span>
   help me to solve.
</div>

我选择了文本,我想在整个文本中获取此文本的start_index(this case = 0)和last_index(此案例= 39),而不包含类pivot

小提琴:http://jsfiddle.net/a7bxp/1/

1 个答案:

答案 0 :(得分:-1)

像这样的东西应该给你一个去:

function getSelectionText() {
    var text = "";
    if (window.getSelection) {
        text = window.getSelection().toString();
    } else if (document.selection && document.selection.type != "Control") {
        text = document.selection.createRange().text;
    }
    return text;
}



$('#your_button').click(function() {
   var whole_text = $('#content').text();
   var selected_text = getSelectionText();
   var index_of = whole_text.indexOf(selected_text);
   var end_of = index_of + selected_text.length;
});

我从这里接受了这个功能:Get the Highlighted/Selected text

这是一个有效的工作: http://jsfiddle.net/a7bxp/