我有一个contenteditable =“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>
的Javascript
$('div#selector').on('mouseup', function (){
alert(document.queryCommandValue('backColor'));
});
示例:http://jsfiddle.net/4Wk2X/11/
你知道为什么会这样吗?
答案 0 :(得分:1)
答案 1 :(得分:1)
我设法通过使用选择的父级然后使用CSS background-color属性来使其工作。
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'));
});
答案 2 :(得分:0)
这是我的想法(不是测试):
alert($(document.getSelection().anchorNode).css('background-color'));
答案 3 :(得分:0)
$(window.getSelection().focusNode.parentNode).css('background-color')
有效。
$(window.getSelection().focusNode.parentNode)
找到文本的父节点,它是具有相关css属性的父节点。
更准确地说,我们将获得结束选择的节点的父节点。
如果您想要选择的开始,可以使用$(window.getSelection().anchorNode.parentNode)
。由于选择可以包含许多背景颜色,您必须选择。
答案 4 :(得分:0)
document.execCommand('styleWithCSS',false,true);
value = document.queryCommandValue('backColor');
document.execCommand('styleWithCSS',false,false);
效果很好。