我正在努力解決一個實際上直截了當的問題:在Internet Explorer中,我想在當前插入位置插入純文本。這對於簡單的TEXTAREA元素來說確實很好,但它並不完全適用於我可以編輯的IFRAME。在插入位置插入文本到可編輯的IFRAME(IE)
在我使用的腳本中,我從IFRAME的文檔中創建一個TextRange對象,我使用它將HTML文本粘貼到光標位置。
<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');"/>
當我在IFRAME中選擇一些文本時,選擇將被替換爲「foo」 - 這是預期的行爲。但是當我在文本中的某處插入插入符號時,插入將無法使用。
這是一種常見的行爲,因爲我只是將光標放在某處,或者它是IE中可編輯IFRAME的錯誤,因爲它對於簡單的TEXTAREA元素來說工作得很好,所以「沒有真正的選擇」?
是否有解決方法?
我有[非常相同的問題](http://stackoverflow.com/questions/5104102/paste-into-iframe-at-caret-position)。它必須是可能的,因爲wordpress這樣做。 – Alex 2011-03-17 11:59:33