问题
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