我正在为web浏览器开发Rich Text Editor,我想在RTE/ContentEditable元素中使用当前字体颜色和大小的值。是否有一些预先选择的函数来获取这些值,比如execCommand,它直接与ContentEditable元素连接?或者我应该使用一些文本范围的jQuery库来获得这些属性吗?
您可以使用document.queryCommandValue()
在所有主要浏览器中获取当前选择的颜色和字体大小:
现场演示:http://jsfiddle.net/timdown/AJBsY/
代码:
var colour = document.queryCommandValue("ForeColor");
var fontSize = document.queryCommandValue("FontSize");
但是,不同浏览器的结果不一致,并且FontSize
命令只适用于HTML <font>
元素中使用的字体大小1-7,而不是CSS,因此您最好掌握包含所选内容的元素,并使用window.getComputedStyle()
/currentStyle
:检查其CSS属性
现场演示:http://jsfiddle.net/timdown/K4n2j/
代码:
function getComputedStyleProperty(el, propName) {
if (window.getComputedStyle) {
return window.getComputedStyle(el, null)[propName];
} else if (el.currentStyle) {
return el.currentStyle[propName];
}
}
function reportColourAndFontSize() {
var containerEl, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
containerEl = sel.getRangeAt(0).commonAncestorContainer;
// Make sure we have an element rather than a text node
if (containerEl.nodeType == 3) {
containerEl = containerEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
containerEl = sel.createRange().parentElement();
}
if (containerEl) {
var fontSize = getComputedStyleProperty(containerEl, "fontSize");
var colour = getComputedStyleProperty(containerEl, "color");
alert("Colour: " + colour + ", font size: " + fontSize);
}
}
这是一个改进,但浏览器仍然存在不一致之处,例如单位或颜色格式不同。