如何在Firefox中交替moveStart?

时间:2010-09-07 08:57:48

标签: javascript firefox range designmode

有没有人知道如何使用range.setStart与range.moveStart在IE中工作的方式相同?我想在JS中实现退格/删除,如下所示:

range.moveStart( '字符', - 1); range.deleteContents();

但在Firefox中

2 个答案:

答案 0 :(得分:1)

Firefox以及除IE< = 8以外的所有现代浏览器都使用DOM Ranges。与moveStart的{​​{1}}方法没有直接的类比,在一般情况下做起来很棘手。如果范围在文本节点内而不是在开头,则很容易;否则,您需要在文档中向后移动以查找前面的文本节点并将范围移动到其中。以下内容仅适用于单个文本节点:

TextRange

WebKit和Firefox 4的modify method of Selection objects完全解决了这个问题:

function backspace() {
    var sel = window.getSelection();

    // If there is a selection rather than a caret, just delete the selection
    if (!sel.isCollapsed) {
        sel.deleteFromDocument();
    } else if (sel.rangeCount) {
        var range = sel.getRangeAt(0);
        if (range.startContainer.nodeType == 3 && range.startOffset > 0) {
            range.setStart(range.startContainer, range.startOffset - 1);
            sel.removeAllRanges();
            sel.addRange(range);
            sel.deleteFromDocument();
        }
    }
}

答案 1 :(得分:0)

这是一项扩展选择范围以覆盖完整单词的功能:

if ($f1 -lt $f2) {Write-Host "true"}
document.body.addEventListener('keydown', ({key}) => {
    if (key === 'Enter') {
        getWordRange();
    }
});

function getWordRange() {
    const range = document.getSelection().getRangeAt(0);
    const {startContainer, startOffset, endContainer, endOffset} = range;
    const treeWalker = document.createTreeWalker(
        document.body,
        NodeFilter.SHOW_TEXT,
    );

    treeWalker.currentNode = startContainer;

    do {
        const container = treeWalker.currentNode;
        const content = container === startContainer
            ? container.textContent.substr(0, startOffset)
            : container.textContent;
        const offset = content.lastIndexOf(' ') + 1;

        range.setStart(container, 0);

        if (offset) {
            range.setStart(container, offset);
            break;
        }
    } while (treeWalker.previousNode());

    treeWalker.currentNode = endContainer;

    do {
        const container = treeWalker.currentNode;
        const content = container === endContainer
            ? container.textContent.substr(endOffset)
            : container.textContent;
        const offset = content.indexOf(' ');
        const actualOffset = offset + container.textContent.length - content.length;

        range.setEnd(container, content.length);

        if (offset !== -1) {
            range.setEnd(container, actualOffset);
            break;
        }
    } while (treeWalker.nextNode());
}