I'm struggling with an actually straighforward problem: In Internet Explorer I want to insert plain text at the current caret position. This works really fine for simple TEXTAREA elements but it doesn't entirely work for editable IFRAMEs, which is what I have.
In the script I use I am creating a TextRange object from the document of the IFRAME which I use to paste the text as HTML at the cursor position.
<iframe id="editable">
<html>
<body>
Some really boring text.
</body>
</html>
</iframe>
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
doc.body.innerHTML = iframe.textContent || iframe.innerHTML;
// Make IFRAME editable
if (doc.body.contentEditable) {
doc.body.contentEditable = true;
}
}
function insert(text) {
var iframe = document.getElementById('editable');
var doc = iframe.contentDocument || iframe.contentWindow.document;
iframe.focus();
if(typeof doc.selection != 'undefined') {
var range = doc.selection.createRange();
range.pasteHTML(text);
}
}
</script>
<input type="button" value="Insert" onClick="insert('foo');"/>
When I select some text in the IFRAME, the selection will be replaced with "foo" - this is expected behaviour. But when I just place the caret somewhere in the text, the insertion won't work.
Is this common behaviour, as there is "no real selection" for the case that I just place the cursor somewhere or is it a bug with editable IFRAMEs in IE, since it works pretty well with simple TEXTAREA elements?
Is there a workaround?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…