Get x, y position of selection relative to a contenteditable div

筅森魡賤 提交于 2019-12-22 15:53:12

问题


I have a contenteditable div and I need to get the x and y position in pixels of the current selection (i.e. of the caret). What I have now is a method which gets the selection relative to the window i.e. window.getSelection(). What I found are methods which return the position in offsets relative to the div node.

Do you have any ideas about this or maybe a plugin? I found plugins that return cursor positions relative to a text area but unfortunately not for a content editable div.

Here is the code I have right now:

function getSelectionCoords() {
    var sel = document.selection, range;
    var x = 0, y = 0;
    if (sel) {
        if (sel.type != "Control") {
            range = sel.createRange();

            range.collapse(true);
            x = range.boundingLeft;
            y = range.boundingTop;
        }
    } else if (window.getSelection) {
        sel = window.getSelection();
        if (sel.rangeCount) {
        range = sel.getRangeAt(0).cloneRange();

        if (range.getClientRects()) {
            range.collapse(true);
            var rect = range.getClientRects()[0];

            x = rect.left;
            y = rect.top;
        }
      }
    }
    return { x: x, y: y };
 }

Thanks for your help.

来源:https://stackoverflow.com/questions/16524842/get-x-y-position-of-selection-relative-to-a-contenteditable-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!