在dbcllicking contenteditable中的文本时阻止选择下一个dom

时间:2015-07-01 22:51:29

标签: jquery html contenteditable

我有以下contenteditable div,混合文本和dom如下:

some text<span> which i would </span><span>like to select </span>

我的问题是,我想防止双击一个单词来选择span arround。例如,如果我双击“&#39;”这个词,它只选择这个词并且它是所需的行为。但问题是,如果我选择单词&#39; will&#39;,它会选择&#39; would&#39;。我怎样才能选择&#39; would&#39;没有跨越双重事件?

我尝试在前后添加空格,但没有结果。

1 个答案:

答案 0 :(得分:0)

只需添加这个小小的javascript片段,就可以在span元素中选择单个单词:

$('span').dblclick(function(e){
    e.preventDefault();
    var selection = window.getSelection();
    if (selection.toString().indexOf(' ') > -1)
    {
        var range = selection.getRangeAt(0);
        var start = range.startOffset;
        var finish = range.endOffset - 1;
        setSelectionRange(this, start, finish);
    }
});

function getTextNodesIn(node) {
    var textNodes = [];
    if (node.nodeType == 3) {
        textNodes.push(node);
    } else {
        var children = node.childNodes;
        for (var i = 0, len = children.length; i < len; ++i) {
            textNodes.push.apply(textNodes, getTextNodesIn(children[i]));
        }
    }
    return textNodes;
}

function setSelectionRange(el, start, end) {
    if (document.createRange && window.getSelection) {
        var range = document.createRange();
        range.selectNodeContents(el);
        var textNodes = getTextNodesIn(el);
        var foundStart = false;
        var charCount = 0, endCharCount;

        for (var i = 0, textNode; textNode = textNodes[i++]; ) {
            endCharCount = charCount + textNode.length;
            if (!foundStart && start >= charCount
                    && (start < endCharCount ||
                    (start == endCharCount && i <= textNodes.length))) {
                range.setStart(textNode, start - charCount);
                foundStart = true;
            }
            if (foundStart && end <= endCharCount) {
                range.setEnd(textNode, end - charCount);
                break;
            }
            charCount = endCharCount;
        }

        var sel = window.getSelection();
        sel.removeAllRanges();
        sel.addRange(range);
    } else if (document.selection && document.body.createTextRange) {
        var textRange = document.body.createTextRange();
        textRange.moveToElementText(el);
        textRange.collapse(true);
        textRange.moveEnd("character", end);
        textRange.moveStart("character", start);
        textRange.select();
    }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
some text<span> which i would </span><span>like to select </span>