开发者

Highlighting text problem

I am fixing an editor and I have highlighting text problem.

I got this co开发者_如何学运维de for checking what have the user highlighted (more details below the code):

function getSelectionHTML()
{
    var iframe = document.getElementById(theEditorID);
    var win, doc = iframe.contentDocument;
    if(doc)
        win = doc.defaultView;
    else
    {
        win = iframe.contentWindow;
        doc = win.document;
    }
    var userSelection;

    if(win.getSelection)
    {
        userSelection = win.getSelection();
        if(userSelection.getRangeAt)
            var range = userSelection.getRangeAt(0);
        else
        {
            var range = document.createRange();
            range.setStart(userSelection.anchorNode, userSelection.anchorOffset);
            range.setEnd(userSelection.focusNode, userSelection.focusOffset);
        }
        var clonedSelection = range.cloneContents();
        var div = document.createElement('div');
        div.appendChild(clonedSelection);
        callIcons(div.innerHTML);
    }
    else if(doc.selection)
    {
        userSelection = document.selection.createRange();
        callIcons(userSelection.htmlText);
    }
};

When the user highlight some bold text and some other italic text i got this output:

<b>some text</b><i>some other text</i>

But when the user highlight only bold text i got this output (there is no 'bold' tag):

some text

You can check that, live, here - http://brownfolder.com/06/ You'll see an alert after highlighting some text.

Do you have any idea how can I fix this?

Thanks in advance.


Browsers vary over whether they include the surrounding tags in the selection. They usually don't include the surrounding tags if the selection is entirely contained within the tags. It's possible to walk up the DOM from the start of the selection and check if each element is a <b> tag. But if the iframe you're working with uses contenteditable, there's no guarantee it will bold with <b> tags. There are other ways the text might be bolded: IE usually adds <STRONG> tags to bold, and Firefox and WebKit may use <span style="font-weight:bold>.

It's probably better to use queryCommandState('bold') on the iframe document instead.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜