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

前端 未结 1 1451
既然无缘
既然无缘 2020-12-10 08:46

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 TE

相关标签:
1条回答
  • 2020-12-10 08:54

    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);
    };
    
    0 讨论(0)
提交回复
热议问题