在我工作的项目中,使用了contetbuilder.js。 我需要确定用户选择的文本的字体系列之间是否存在差异。 现在该函数如下所示:
reportFontSettings = function() {
function getComputedStyleProperty(el, propName) {
if (window.getComputedStyle) {
return window.getComputedStyle(el, null)[propName];
} else if (el.currentStyle) {
return el.currentStyle[propName];
}
}
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");
var fontFamily = getComputedStyleProperty(containerEl, "fontFamily");
return {"Colour": colour, "FontFamily": fontFamily, "FontSize": fontSize};
}
return null;
};
函数reportFontSettings()返回所选文本的颜色,字体系列和字体大小。
现在,他始终以文本的父元素为导向。
如果从多种字体中选择了文本,我需要该函数返回“ nofont”,以便用户有机会在编辑器中选择字体。
<span class="lato">
lato1 <font class="roboto> roboto1 </font> lato2 <font class="roboto> roboto2 </font> lato3
</span>
lato1 roboto1 lato2 roboto2 lato3
我想我需要选择从roboto1到roboto2的文本。中间也有不同字体的lato2文本,因此我需要返回“ nofont”。如果它们之间没有其他字体,那么我将返回字体名称,例如:“ roboto”
请在此处进行测试:JSFiddle