jquery window.getSelection()偏移HTML标记?

nnt7mjpx  于 2023-10-17  发布在  jQuery
关注(0)|答案(2)|浏览(112)

如果我有以下HTML:

<div class="content">
Vivamus <span>luctus</span> urna sed urna ultricies ac tempor dui sagittis.
</div>

我在mouseup上运行一个事件,它可以看到所选文本的范围:

$(".content").on("mouseup", function () {
    var start = window.getSelection().baseOffset;
    var end = window.getSelection().focusOffset;
    if (start < end) {
        var start = window.getSelection().baseOffset;
        var end = window.getSelection().focusOffset;
    } else {
        var start = window.getSelection().focusOffset;
        var end = window.getSelection().baseOffset;
    }
    console.log(window.getSelection());
    console.log(start + ", " + end);
});

我从内容中选择单词Vivamus,它将记录1, 8,因为这是选择的范围。

但是,如果,我选择单词urna,它将记录15, 20,但不会考虑HTML的<span>元素。

focusOffsetbaseOffset是否也适用于HTML标签,而不仅仅是文本?

zsohkypk

zsohkypk1#

更新

示例:http://jsfiddle.net/FLwxj/61/
Using a clearSelection() functiona replace approach,我能够达到预期的结果。

var txt = $('#Text').html();
$('#Text').html(
    txt.replace(/<\/span>(?:\s)*<span class="highlight">/g, '')
);
clearSelection();

资料来源:

下面你会找到一些解决问题的方法。我把它们按照代码效率的顺序排列。

工作解决方案

window.highlight = function() {
    var selection = window.getSelection().getRangeAt(0);
    var selectedText = selection.extractContents();
    var span = document.createElement("span");
    span.style.backgroundColor = "yellow";
    span.appendChild(selectedText);
    span.onclick = function (ev) {
    this.parentNode.insertBefore(
        document.createTextNode(this.innerHTML), 
        this
    );
    this.parentNode.removeChild(this);
    }
    selection.insertNode(span);
}
$(".content").on("mouseup", function () {
   makeEditableAndHighlight('yellow'); 
});

function makeEditableAndHighlight(colour) {
    sel = window.getSelection();
    if (sel.rangeCount && sel.getRangeAt) {
    range = sel.getRangeAt(0);
    }
    document.designMode = "on";
    if (range) {
    sel.removeAllRanges();
    sel.addRange(range);
    }
    // Use HiliteColor since some browsers apply BackColor to the whole block
    if (!document.execCommand("HiliteColor", false, colour)) {
    document.execCommand("BackColor", false, colour);
    }
    document.designMode = "off";
}

function highlight(colour) {
    var range, sel;
    if (window.getSelection) {
    // IE9 and non-IE
    try {
        if (!document.execCommand("BackColor", false, colour)) {
        makeEditableAndHighlight(colour);
        }
    } catch (ex) {
        makeEditableAndHighlight(colour)
    }
    } else if (document.selection && document.selection.createRange) {
    // IE <= 8 case
    range = document.selection.createRange();
    range.execCommand("BackColor", false, colour);
    }
}

其他有用的解决方案:

dddzy1tm

dddzy1tm2#

const range = selection.getRangeAt(); const newTag = document. documentElement(tag);
transmitted. transmitted(transmitted);

相关问题