javascript - 如何判断当前选中文本的出现顺序?

标签 javascript jquery css

我想知道在我的内容 div (.entry-content) 中选择了当前所选文本的哪一次出现。

我当前的 fiddle 是根据以前的答案构建的,它做对了......有时!

http://jsfiddle.net/FTWLJ/10/

如果您选择单词 Maecenas(第一个单词),当您选择第一个单词时它会给出正确的出现。尝试使用第二段的第一段,它给出了错误的出现。应该是 3。

它有时似乎工作但不可靠,这可能是使用 elementFromPoint( x, y )

当你选择完整的单词时,它似乎不起作用。当您选择半个单词和另一个半个单词时,它会起作用。

$('.entry-content').on('click',function(e){

    //get the x and y coords
    var offset = $(this).offset(),
        x = e.clientX - offset.left,
        y = e.clientY - offset.top,
        text;

    //get the highlighted text
    if(window.getSelection){
        text = window.getSelection().toString();
    }else if (document.selection && document.selection.type != 'Control'){
        //for IE prior to 9
        text = document.selection.createRange().text;
    }

    //check if the text is empty or just spaces   
    if($.trim(text).length){

        //wrap each word similar to the highlighted text with <span>
        var regex = new RegExp(text,'g')
        $('.entry-content').html($('.entry-content').html().replace(regex, '<span class="highlight">'+text+'</span>'));

        //get the new span index situating on coords
        var el = document.elementFromPoint(x, y),
            occurrence = $(el).index()+1,
            exist = $('span').length;       

        alert(exist+' exist | occurrence: '+occurrence);

        //remove the <span> wrapper            
        $('span').contents().unwrap();

    }
});

有人对此有可靠的解决方案吗?

最佳答案

这将返回元素相对于其父元素的索引:

occurrence = $(el).index()+1

您想要的是它与 所有 跨度相关的索引:

occurrence = $('span').index(el)+1

Fiddle

关于javascript - 如何判断当前选中文本的出现顺序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37033422/

相关文章:

javascript - Stripe : How to attach a debit-card for payouts

html - 为什么我不能让导航栏在页面上居中?

c# - 禁止在 ASP.NET 中查看上一页

javascript -/* @flow strict */在所有源文件上

jquery - 使用 jQuery 可拖动和可调整大小与 jquery 碰撞 1.0.1 的奇怪行为

javascript - 现代 css/jquery 气泡动画

javascript - 在已存储在变量中的对象中按类查找特定元素

javascript - Jasny Bootstrap 更改

css - Codeigniter 本地主机 CSS

javascript - jquery 事件监听器在刷新我的 jquery 数据表后不起作用?