Inserting text into an editable IFRAME at the caret position (IE)

允我心安 提交于 2019-11-28 10:30:34

You may find it works if you use onmousedown rather than onclick in your button.

UPDATE

The reason why this makes a difference is that the click event fires after the iframe has lost focus (which destroys a collapsed selection in IE) whereas mousedown fires before.

FURTHER UPDATE

You could also try fixing this in IE by saving/restoring the selected TextRange as the iframe loses/receives focus. Something like this should work:

function fixIframeCaret(iframe) {
    if (iframe.attachEvent) {
        var selectedRange = null;
        iframe.attachEvent("onbeforedeactivate", function() {
            var sel = iframe.contentWindow.document.selection;
            if (sel.type != "None") {
                selectedRange = sel.createRange();
            }
        });
        iframe.contentWindow.attachEvent("onfocus", function() {
            if (selectedRange) {
                selectedRange.select();
            }
        });
    }
}

window.onload = function() {
    var iframe = document.getElementById('editable');
    fixIframeCaret(iframe);
};
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!