带有javascript的选定文本的背景色

Background color of selected text with javascript

本文关键字:文本 背景色 javascript 带有      更新时间:2023-09-26

我有一个内容编辑="true"的div,我想获取所选文本的背景颜色。它在Chrome中工作正常,但在Firefox中一直返回"透明"而失败。现在我尝试这样做。.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>

爪哇语

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

示例:http://jsfiddle.net/4Wk2X/11/

你知道为什么会这样吗?

我让它像这样工作:

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

看小提琴

我设法通过使用选择的父级和 CSS 背景颜色属性来使其工作。

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'));
});

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

>$(window.getSelection().focusNode.parentNode).css('background-color')有效。

$(window.getSelection().focusNode.parentNode) 查找文本的父节点,并且它是具有相关 CSS 属性的父节点。

更准确地说,我们将获得您结束选择的节点的父节点。 如果要开始选择,可以使用$(window.getSelection().anchorNode.parentNode)。由于选择可以包含许多背景颜色,因此您必须选择。

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

效果很好。

这是我

的想法(不是测试):

 alert($(document.getSelection().anchorNode).css('background-color'));