获取光标在TinyMCE中的位置或光标所在的行数 [英] Get cursor position or number of line on which the cursor is in TinyMCE

查看:898
本文介绍了获取光标在TinyMCE中的位置或光标所在的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何获取光标在TinyMCE中的位置或光标在TinyMCE中的行数?

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

推荐答案

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

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;

函数getBoundingClientRect()用于创建一个盒子,从中可以获取多个定位信息.请注意,我们需要使用标记元素并稍后重新设置插入符号.

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.

更新:lineHeight的信息

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 );

这篇关于获取光标在TinyMCE中的位置或光标所在的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆