Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
261 views
in Technique[技术] by (71.8m points)

javascript - Restore cursor position after changing contenteditable

There is html like this:

<div contenteditable="true" class="value research-form thumbnail">
 Some text here
 </div>

And content of div should dynamicly highlight some words while user types e.g make something like:

 <div contenteditable="true" class="value research-form thumbnail">
 Some text here <span style="background-color: yellow">highlight</div> it
 </div>
 <script>
    $(document).ready(function () {
        var input = $('#textarea').on('input', function (event) {
            var newText = input.text().replace('highlight', '<span style="background-color: yellow">highlight</div>');
            input.html($.parseHTML(newText));
        });
    });
</script>

But there is a problem: when I refresh text in div cursor moves at start of the text in input.

Is there any ways to restore cursor position after changing contenteditable value? Or maybe there is other way to get the same effect?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I found the solution.

Here is a complete code:

<div class="container" style="margin-top: 10px">

    <div class="thumbnail value" contenteditable="true">

    </div>

</div>

<script>
    $(document).ready(function () {
        function getCaretCharacterOffsetWithin(element) {
            var caretOffset = 0;
            var doc = element.ownerDocument || element.document;
            var win = doc.defaultView || doc.parentWindow;
            var sel;
            if (typeof win.getSelection != "undefined") {
                sel = win.getSelection();
                if (sel.rangeCount > 0) {
                    var range = win.getSelection().getRangeAt(0);
                    var preCaretRange = range.cloneRange();
                    preCaretRange.selectNodeContents(element);
                    preCaretRange.setEnd(range.endContainer, range.endOffset);
                    caretOffset = preCaretRange.toString().length;
                }
            } else if ((sel = doc.selection) && sel.type != "Control") {
                var textRange = sel.createRange();
                var preCaretTextRange = doc.body.createTextRange();
                preCaretTextRange.moveToElementText(element);
                preCaretTextRange.setEndPoint("EndToEnd", textRange);
                caretOffset = preCaretTextRange.text.length;
            }
            return caretOffset;
        }

        function setCaretPosition(element, offset) {
            var range = document.createRange();
            var sel = window.getSelection();

            //select appropriate node
            var currentNode = null;
            var previousNode = null;

            for (var i = 0; i < element.childNodes.length; i++) {
                //save previous node
                previousNode = currentNode;

                //get current node
                currentNode = element.childNodes[i];
                //if we get span or something else then we should get child node
               while(currentNode.childNodes.length > 0){
                  currentNode = currentNode.childNodes[0];
               }

                //calc offset in current node
                if (previousNode != null) {
                    offset -= previousNode.length;
                }
                //check whether current node has enough length
                if (offset <= currentNode.length) {
                    break;
                }
            }
            //move caret to specified offset
            if (currentNode != null) {
                range.setStart(currentNode, offset);
                range.collapse(true);
                sel.removeAllRanges();
                sel.addRange(range);
            }
        }

        function onInput(event) {
            var position = getCaretCharacterOffsetWithin(input.get(0));
            var text = input.text();
            text = text.replace(new RegExp('\btest\b', 'ig'), '<span style="background-color: yellow">test</span>');
            input.html($.parseHTML(text));
            setCaretPosition(input.get(0), position);
        }

        var input = $('.value').on('input',onInput);

        //content should be updated manually to prevent aditional spaces
        input.html('simple input test example');
        //trigger event
        onInput();
    });
</script>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...