Get cursor position or number of line on which the cursor is in TinyMCE

偶尔善良 提交于 2019-12-11 02:24:31

问题


How to get the cursor position in TinyMCE or the number of line on which the cursor is in TinyMCE?


回答1:


Here is the part of a function from one of my own plugins i use to get the actual line number:

        var ed = tinymce.get('my_editor_id');
        var bm = ed.selection.getBookmark();
        var $marker = $(ed.getBody()).find('#'+bm.id);
        var elem = ed.getDoc().getElementById(bm.id+'_start');
        try {
            box = elem.getBoundingClientRect();
        } 
        catch(e) 
        {
                            // should not happen
            console.log('error creating box: ' + e);
        }

        var doc = ed.getDoc(),
            docElem = doc.documentElement,
            body = ed.getBody(),
            win = ed.getWin(),
            clientTop  = docElem.clientTop  || body.clientTop  || 0,
            clientLeft = docElem.clientLeft || body.clientLeft || 0,
            scrollTop  = win.pageYOffset || jQuery.support.boxModel && docElem.scrollTop  || body.scrollTop,
            scrollLeft = win.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.scrollLeft,
            top  = box.top  + scrollTop  - clientTop,
            left = box.left + scrollLeft - clientLeft;

        // set Bookmark
        ed.selection.moveToBookmark(bm);

        var caret_line = Math.floor( (top) / lineHeight ) + 1;

The function getBoundingClientRect() is used to create a box from which we can get several positioning information. Be aware the we need to use a marker-element and reset the caret later on.

Update: Info for lineHeight

            // get height of row: eighter line-height or min-height
            if ( $(ed.getBody()).find('p:first').css('line-height') != 'normal'){
                lineHeight = $(ed.getBody()).find('p:first').css('line-height') ;
            }
            else {
                lineHeight = $(ed.getBody()).find('p:first').css('min-height');
            }

            var lineHeight = lineHeight.substr(0, lineHeight.length -2 );


来源:https://stackoverflow.com/questions/11860175/get-cursor-position-or-number-of-line-on-which-the-cursor-is-in-tinymce

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