我正在为 Web 浏览器开发富文本编辑器,我想在 RTE/ContentEditable 元素中使用当前字体颜色和大小的值。是否有一些预选函数来获取这些值,例如直接与 ContentEditable 元素相关联的 execCommand?或者我应该使用一些文本范围的 jQuery 库来获取这些属性吗?
最佳答案
您可以使用 document.queryCommandValue()
在所有主流浏览器中获取当前选择的颜色和字体大小:
现场演示:http://jsfiddle.net/timdown/AJBsY/
代码:
var colour = document.queryCommandValue("ForeColor");
var fontSize = document.queryCommandValue("FontSize");
但是,结果在浏览器和 FontSize
之间是不一致的命令仅适用于 HTML 中使用的字体大小 1-7 <font>
元素而不是 CSS,因此您最好获取包含选择的元素并使用 window.getComputedStyle()
检查其 CSS 属性/currentStyle
:
现场演示: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);
}
}
这是一个改进,但仍然存在浏览器不一致的问题,例如不同的单位或颜色格式。
关于javascript - ContentEditable - 获取当前字体颜色/大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8770008/