How to select range of text in tinymce editor in firefox
I am trying to select a specified text in TinyMCE editor using JavaScript in mozilla firefox. So essentially I want to select 'Hello World' in the text below?
<body class="mceContentBody " id="tinymce" dir="ltr"> <p>Hi there Hello World this is amazing<br_mce_bogus="1"></p></body>
I successfully wrote a JavaScript to 开发者_运维百科select a range of text in tinymce editor in IE (since IE uses Text range object, It was easy to move the range). I still have problems selecting the text I want in mozilla though. It selects the entire content but not sure how to select the content I want. Anybody? Or can anyone give me example on how to use tinyMCE API to select a specified text?
var range = document.createRange();
var start = document.getElementById('tinymce');
range.setStart(start, 0);
range.setEnd(start, start.childNodes.length);
window.getSelection().addRange(range);
Using the startOffset and endOffset other than 0 and 1 respectively (in setStart and setEnd), JavaScript throws error
Index or size is negative or greater than the allowed amount
There is an API in TinyMCE for doing this, but I don't know it, so I'll give you the DOM Range version. You need to get hold of the text node containing the text you want:
var range = document.createRange();
var start = document.getElementById('tinymce');
var textNode = start.getElementsByTagName('p')[0].firstChild;
range.setStart(textNode, 9);
range.setEnd(textNode, 20);
window.getSelection().addRange(range);
IE's TextRange
and DOM's Range
are conceptually very different: the former focusses almost exclusively on text content with very little regard for DOM node boundaries while the latter focusses entirely on DOM nodes (including text nodes and elements) and offsets within them.
精彩评论