سؤال

I have a div with contenteditable="true" and I want to get the background color of the selected text. It works fine in Chrome but it fails in Firefox by returning "transparent" all the time. Here is now I try to do it. HTML:

<div contenteditable="true" id="selector" style="background-color: rgb(255,255,0);">
    Test back<span style="background-color: rgb(255,0,0);">ground</span> color.
</div>

Javascript

$('div#selector').on('mouseup', function (){
    alert(document.queryCommandValue('backColor'));
});

Sample: http://jsfiddle.net/4Wk2X/11/

Do you have any idea why this happens?

هل كانت مفيدة؟

المحلول 2

I managed to get it work by using the parent of the selection and then the CSS background-color property.

var selectionParent = function () {
    var parent = null, sel;

    if (window.getSelection) {
        sel = window.getSelection()
        if (sel.rangeCount) {
            parent = sel.getRangeAt(0).commonAncestorContainer
            if (parent.nodeType != 1) {
                parent = parent.parentNode
            }
        }
    } else if ( (sel = document.selection) && sel.type != "Control") {
        parent = sel.createRange().parentElement()
    }

    return parent
}

$('div#selector').on('mouseup', function (){
    alert(selectionParent().css('background-color'));
});

See http://jsfiddle.net/4Wk2X/14/

نصائح أخرى

I got it to work like this:

$('div#selector').on('mouseup', function (){
    alert($(this).css('color'));
});

See the fiddle

$(window.getSelection().focusNode.parentNode).css('background-color') works.

$(window.getSelection().focusNode.parentNode) finds the parent node of your text , and it's the parent node that has the relevant css property.

To be more precise, we will get the parent node of the node where you ended your selection. $(window.getSelection().anchorNode.parentNode) can be used if you want the start of the selection. as a selection can contain many backgroundcolors, you will have to choose.

document.execCommand('styleWithCSS',false,true);
value = document.queryCommandValue('backColor');
document.execCommand('styleWithCSS',false,false);

It works well.

This is my idea(not test):

 alert($(document.getSelection().anchorNode).css('background-color'));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top