Changes to selection and range functionality in IE

2019-08-15 00:34发布

问题:

I'm having to debug a WYSIWYG javascript based HTML editor that is failing in IE8. It's only designed for use in IE so that should simplify the solution. Here's the existing code that is failing:

function isAllowed() {
    var sel
    var obj

        sel = foo.document.selection

        if (sel.type != "Control")
        {
            obj = sel.createRange().parentElement()
        } else {
            obj = sel.createRange()(0)
        }

        if (obj.isContentEditable) {
            foo.focus()
            return true
        } else {
            return false
        }
}

Essentially what is happening is that if you select some text and click say the insert image button it first runs this isAllowed function to see if the text you've selected is editable (i.e. within the iframe that is ContentEditable).
This seems to be breaking down in IE8 at at either document.selection or createRange().

The problem is that when you don't select any text with your mouse and click somewhere in the editable region, sel.createRange().parentElement() seems to return an element outside of the iframe and it's thus not ContentEditable and the function returns false.

I'm wondering if anyone could shed any insight on to what has changed in IE8's implementation of selections and ranges that would cause this behaviour?

回答1:

Ok, the answer was pretty simple! It must be a change in the way IE8 keeps the focus on the iframe, by adding foo.focus(); to the code below, everything works as expected. Hope this helps someone, but it probably won't if their code was written properly in the first place :)

function isAllowed() {
    var sel;
    var obj;

        foo.focus();
        sel = foo.document.selection;

        if (sel.type != "Control")
        {
            var rng = sel.createRange();
            obj = rng.parentElement();
        } else {
            obj = sel.createRange()(0);
        }

        if (obj.isContentEditable) {
            foo.focus();
            return true;
        } else {
            return false;
        }
}


回答2:

Have you considered using a debugger or putting alerts into the javscript so you can figure out what is happening. Figure out which element is being returned and maybe you will find your problem. It's possible it returning some parent element instead of the iframe (I'm just guessing here). Also, I am not sure why it would run if they have only clicked in the area though. Maybe I misunderstanding something.