获得光标位置或线的数目在其上光标在TinyMCE的(Get cursor position or n

2019-09-21 00:05发布

如何获得在TinyMCE的光标位置或光标在TinyMCE的行号?

Answer 1:

这是从我自己的插件,我用它来获得实际的行号的一个函数的一部分:

        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;

该功能getBoundingClientRect()用于创建一个框,从中我们可以得到几个定位信息。 要知道,我们需要用一个标志元素,稍后重新插入符。

更新:信息为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 );


文章来源: Get cursor position or number of line on which the cursor is in TinyMCE