开发者

Javascript + How to get the index w.r.t the parent Node of selection + Browsers Other than IE

Hi I want to get the selection start and end index with respect to the parent node of the selected text. I am able to do this in IE. However in other browsers like Firefox, Opera, Safari and Chrome, I am able to access the selection and the index of the selected text. But my requirement is to get the index w.r.t the parent node开发者_运维问答 and not the selected node. I am in need of a solution that supports all browsers - Firefox, Opera, Safari and Chrome

    if (window.getSelection) { 
                     alert("Other browser");     
                     sel = window.getSelection();

                        if(sel != '') {
               //alert(sel.anchorNode.parentNode.nodeName);
             //alert(sel.anchorOffset);
             //alert(sel.focusNode.parentNode.nodeName);
             //alert(sel.focusOffset);                
 }
                    }    
        else if (document.selection) {   
                        txt = document.selection.createRange().text;
                        var range_all = document.body.createTextRange();
                        if (txt!='' )
                        {
                            // Finding start position
                         range = document.selection.createRange();
                            range.collapse(true); 

                         var startParentElement =  range.parentElement();                 

                            range_all.moveToElementText(startParentElement);
                            for (var sel_start = 0; range_all.compareEndPoints('StartToStart', range) < 0; sel_start ++)
                                range_all.moveStart('character', 1);
                            range = document.selection.createRange();
                            range.collapse(false); 
                            range_all = document.body.createTextRange();

                         var endParentElement =  range.parentElement();                 
                                                 range_all.moveToElementText(endParentElement);
                            for (var sel_end = 0; range_all.compareEndPoints('StartToEnd', range) < 0; sel_end ++)
                              range_all.moveStart('character', 1);
    alert("sel_start:" + sel_start);
                        alert("sel_end:" + sel_end);
    }}


QuirksMode site can help you here: http://www.quirksmode.org/dom/range_intro.html

You just need to learn how to use the range object in browsers other than IE.


In these browsers you should work with a Range object you get from window.getSelection.

var range = sel.getRangeAt(0).cloneRange();
//range.endContainer, range.startContainer etc.

API: https://developer.mozilla.org/en/docs/Web/API/Range

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜