最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to highlight a given text in TinyMCE? - Stack Overflow

programmeradmin2浏览0评论

I have the following phrase:

The birds fly in the sky near planes.
0123456789012345678901234567890123456
          1         2         3 

How can I highlight in the sky with TinyMce if I know the start(14) and end(23) of the phrase ?

I would like to use the setRng method but I didn't find any sample code.

I have the following phrase:

The birds fly in the sky near planes.
0123456789012345678901234567890123456
          1         2         3 

How can I highlight in the sky with TinyMce if I know the start(14) and end(23) of the phrase ?

I would like to use the setRng method but I didn't find any sample code.

Share Improve this question edited Dec 4, 2011 at 0:43 Ry- 225k56 gold badges492 silver badges498 bronze badges asked Dec 4, 2011 at 0:35 StephanStephan 43.1k66 gold badges244 silver badges340 bronze badges 3
  • Is it required to find the string by position, or would it be sufficient to find the string by the search-string? – Dr.Molle Commented Dec 4, 2011 at 2:34
  • Actually, I send the whole content if tinymce editor to a server. The server then replies back with some information. This information contains start and end of strings to be highlighted. Modifying the information sent by the server is not an option. – Stephan Commented Dec 4, 2011 at 2:40
  • It seems that you implemented a real time collaboration editor on tinymce. Can you please enlight me how did you detect that the user selected a piece of text on tinymce? onselect does not work and I have been looking all over for an alternative. Thanks :) – Bernice Commented Mar 28, 2013 at 19:58
Add a ment  | 

2 Answers 2

Reset to default 5

Here is the solution I came up with :

var ed = tinyMCE.activeEditor;
var range = ed.selection.getRng();
range.setStart(textNode, start);
range.setEnd(textNode, end);
ed.selection.setRng(range); 

Where :

  • textNode can be a DOM text node that you can retrieve with getElementById or any other short-hand properties (parent, nextSibling etc)
  • start and end are respectively the beginning and the end of the text you want to select

I prefer this solution because I only use the tinyMCE API. I don't rely on objects and methods that can change (in behavior, in bugs ...) from browser to browser.

Try:

var range = document.createRange();
var start = document.getElementById('tinymce');
//var textNode = start.getElementsByTagName('p')[0].firstChild;
//edited
var textNode = start.getElementsByTagName('your_tag_where_you_have_the_text')[0].firstChild;
range.setStart(textNode, 14);
range.setEnd(textNode, 23);
window.getSelection().addRange(range);
发布评论

评论列表(0)

  1. 暂无评论