2

contenteditable 中的文本选择给我带来了很大的问题......

我正在尝试以与此代码部分相同的方式获取开始和结束选择点:

http://jsfiddle.net/TjXEG/1/

(因为在 contenteditable 中,有不同的标签,我需要在失去焦点后重新选择可见的选定文本(文本节点?)

我真的很迷茫,有人知道教程或其他东西来理解网络浏览器中的选择吗?

谢谢,叶宝

4

1 回答 1

2

Because I only use Chrome, I chopped off the else since it doesn't apply. So here's the Chrome solution:

Non-editable text. Editable is below:
<div id="test" contenteditable="true">Hello, some <b>bold</b> and <i>italic and <b>bold</b></i> text</div>
<div id="caretPos"></div>
<div id="caretPost"></div>
<script type="text/javascript">
function getCaretCharacterOffsetWithin(element) {
    var begin = 0;
    var end = 0;
    if (typeof window.getSelection != "undefined") {
        var range = window.getSelection().getRangeAt(0);
        var preCaretRange = range.cloneRange();
        preCaretRange.selectNodeContents(element);
        preCaretRange.setEnd(range.startContainer, range.startOffset);
        begin = preCaretRange.toString().length;
        preCaretRange.setEnd(range.endContainer, range.endOffset);
        end = preCaretRange.toString().length;
    }
    return "Selection start: " + begin + "<br>Selection end: " + end;
}

function showCaretPos() {
    var el = document.getElementById("test");
    var caretPosEl = document.getElementById("caretPos");
    caretPosEl.innerHTML =  getCaretCharacterOffsetWithin(el);
}

document.body.onkeyup = showCaretPos;
document.body.onmouseup = showCaretPos;
</script>

Once you understand it, the logic is pretty simple. There is a start and end container. If it is plain text: they will be the same; however, HTML tags fragment the sentence and will make start contain a portion and end contain a different portion.

If you use setStart() where I'm using setEnd() and reverse the parameters as well, it'll be the same as reversing the index (i.e. the end will be 0 instead of the beginning).

So in order to fetch the beginning, you still use setEnd(), except with the start parameters.

于 2012-09-01T05:26:35.407 回答