开发者

Calculating the absolute start and finish of a range (highlighted text) within an editable div

I'm running an experiment to see if I can return that absolute start and end points of a highlighted block of test within a contentEditable (not actually important to the test) div. I'm not building a rich text editor or anything I just want to know how it's done! So all I want to return upon right click (not important, I'm just messing with that too) are two numbers, the absolute distance from the start of the wrapper div to the start of the selection and the absolute distance from the start of the wrapper div to the end of the selection.

I thought Mootools would make this easy but I could only get their implementation to work with forms (i.e. textarea, input etc). So I had a quick bash using Google, and it all worked fine when no tags were involved, e.g. He|llo Wor|ld (where the pipe, |, represents the highlighted range) would return [2, 9] which is correct. However, the moment I add tags to the div to allow colours / formatting these numbers do not make any sense as the range only gives position relative to text nodes and not an absolute value. Any ideas how to get this? I can only imagine it involves some form of horrendous DOM manipulation.

JS:

window.addEvent('domready', function()
    {
        document.body.addEvent('contextmenu', 
            function(e)
            {
                e.stop();
            }
        );

        if(!window.SelectionHandler)
        {
            SelectionHandler = {};
        }

        SelectionHandler.Selector = {};

        SelectionHandler.Selector.getSelected = function()
        {
            var userSelection = '';

            if(window.getSelection)
            {
                userSelection = window.getS开发者_如何学运维election();
            }
            else if(document.getSelection)
            {
                userSelection = document.getSelection();
            }
            else if(document.selection)
            {
                userSelection = document.selection.createRange();
            }

            return userSelection;
        }

        SelectionHandler.Selector.getText = function(userSelection)
        {
            var selectedText = userSelection;

            if(userSelection.text)
            {
                selectedText = userSelection.text;
            }

            return selectedText;
        }

        SelectionHandler.Selector.getRange = function(userSelection)
        {
            if(userSelection.getRangeAt && typeof(userSelection.getRangeAt) != 'undefined')
            {
                var selectedRange = userSelection.getRangeAt(0);
            }
            else
            {
                var selectedRange = document.createRange();
                selectedRange.setStart(userSelection.anchorNode, userSelection.anchorOffset);
                selectedRange.setEnd(userSelection.focusNode, userSelection.focusOffset);
            }

            return selectedRange;
        }

        $('mydiv').addEvent('mousedown', 
            function(event)
            {
                if(event.rightClick)
                {
                    var userSelection   = SelectionHandler.Selector.getSelected();
                    var selectedText    = SelectionHandler.Selector.getText(userSelection);
                    var selectedRange   = SelectionHandler.Selector.getRange(userSelection);

                    // New ranges to add identifiable nodes (must be in that order!?)
                    var endRange = document.createRange();
                    endRange.setStart(selectedRange.endContainer, selectedRange.endOffset);
                    endRange.insertNode(document.createTextNode('!~'));

                    var startRange = document.createRange();
                    startRange.setStart(selectedRange.startContainer, selectedRange.startOffset);
                    startRange.insertNode(document.createTextNode('~!'));

                    // Find the position of our new identifiable nodes (and account for their removal)
                    var div_content = $('mydiv').get('html');
                    var start       = div_content.indexOf('~!');
                    var end         = div_content.indexOf('!~') - 2;

                    // Remove our identifiable nodes (DOESN'T WORK)
                    //startRange.deleteContents();
                    //endRange.deleteContents();

                    // This does work, but obviously loses the selection
                    div_content = div_content.replace('~!', '').replace('!~', '');
                    $('mydiv').set('html', div_content);

                    console.log(start + ' vs ' + end);
                }
            }
        );
    }
);

HTML:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
 <head>
  <title>Edit Range Test</title>
 </head>

 <script type="text/javascript" src="mootools.js"></script>
 <script type="text/javascript" src="edit_range.js"></script>

 <style>
    #mydiv {
        width: 400px;
        height: 400px;
        border: 1px solid #a2a2a2;
        padding: 5px;
    }
 </style>

 <body>
    <h1>Edit Range Test</h1>

    <div id="mydiv" contentEditable="true"><span style="color: red;">Hello</span> World! <span style="color: red;">Hello</span> World! </div>

 </body>
</html>

So when I now select He|llo Wor|ld (where the pipe, |, again represents the highlighted range) it would return [2, 4] when I want [28, 42].

EDIT: I've updated the code to clarify what I am trying to do. It does most of what I wanted to test, but loses the selection and is very scruffy!

Thanks in advance!


First, the information you get from Range objects are about as useful as you can get: for each of the start and end boundaries of the Range you get a DOM node and an offset within that node (a character offset inside a text or comment node or a child node offset otherwise), which completely describes the boundary. What you mean by "absolute start and end points" I imagine is two character offsets within the whole editable element, but that is a slippery concept: it seems simple, but is tricky to pin down. For example, how many characters does a paragraph break count for? A <br>? An <a> element with display: block? Elements such as <script> elements that contain text but are not visible to the user? Elements hidden via display: none? Elements outside the normal document flow, such as those positioned via position: absolute? Multiple consecutive whitespace characters that are rendered as a single visible character by the browser?

Having said all that, I have recently had a go at writing code to do this, and yes, it does involve DOM manipulation (although not that horrendous). It's extremely rudimentary and doesn't deal satisfactorily with any of the above issues, partly because I knocked it up quite quickly for a question on SO, and partly because in general I don't think it's possible to deal nicely in general with all those issues. The following answer provides functions for saving and restoring the selection as character indices within an editable element: replace innerHTML in contenteditable div

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜