【问题标题】:JS complex operation of the selected textJS对选中文本的复杂操作
【发布时间】:2015-10-30 12:00:26
【问题描述】:

伟大的 JavaScript,请帮助。 我需要处理选中文本的复杂操作。

我有一些带有很多html标签的文本,我需要得到一个返回以下结果的函数:

用户选择带有类的特定标签中的文本,例如<div class="text">

并且该功能在以下情况下被激活:

$('.text').mouseup(function (e){...});
  • 返回选择的开头
  • 返回结尾
  • selection 用他的类标识一个特定的标签

此外:

  • 要赋予html标签的字符数,
  • 但您可以排除 一些标签示例,

好的,一些代码,我有什么:

$(function () {
    $('.text').mouseup(function (e){
        $(this).highlight(getSelectionText());
   })
})

this demo

这里我们突出显示了文本的所需部分,但没有返回 正确的位置

另外,文字发布是巧合 字符,我需要它的位置

【问题讨论】:

    标签: javascript jquery text syntax-highlighting highlight


    【解决方案1】:

    你可能想试试这个:

    $(function () {
        $('#detailBoxParagraph').mouseup(function (e){
            var selectedText = getSelectionText();
            $(this).removeHighlight();
            $(this).highlight(selectedText);
    
            var txt = $(this).text();
            var pos = [];
            var i = txt.indexOf(selectedText);
            if(i > -1) {
                pos.push({"start": i+1, "end": i + selectedText.length});
            }
            while (i != -1) {
                i = txt.indexOf(selectedText, i + 1);
                if(i > -1) {
                   pos.push({"start": i+1, "end": i + selectedText.length});
                }
            }
            console.log(pos);
       })
       //alertSelection();
    })
    

    【讨论】:

    • 不幸的是,这是不合适的,因为: - 不会导致字符数,并且在 rastolyanii (left, top) - 如果分配的标签不考虑,我相反他们需要
    • 我更新了上面的代码。您也可以在此处查看代码(jsfiddle.net/LgCjT/152)。
    • 再一次,没有会计 html 标签,当我尝试高亮几次时,我的浏览器 (Chrome) 不知何故崩溃了
    • 是的,它不考虑 html 标签。我所做的是找到以字符为基础突出显示的文本的所有位置。例如: var str = "示例文本示例";如果我突出显示“文本”,“文本”文本的位置将是 8-11,其中 8 是开始,11 是选择的结束。
    • 这就是@serge 的意思吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-13
    • 2021-07-24
    • 1970-01-01
    • 2016-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多