I\'m working on Rich Text Editor for web browser and I want to work with values of current font color and size in the RTE/ContentEditable element. Is there some preselected func
That way you can get all the style that applies on the element you clicked. try the snippet
Element.prototype.isChildOf = function (parent) {
var node = this.parentNode;
while (node !== null) {
if (node === parent) {
return true;
}
node = node.parentNode;
}
return false;
}
function getStyle(el) {
if (!el || !el.style) return {};
let styles = {};
let style = el.getAttribute('style');
if (style) {
let collectStyles = style.split(';');
if (Array.isArray(collectStyles)) {
collectStyles.forEach(style => {
const keyValue = style.split(':');
if (keyValue[1] && keyValue[0])
styles[keyValue[0].trim()] = keyValue[1].trim();
})
}
}
return styles;
}
function getInheirtCss(fromElement, toElement) {
var intailStyle = {};
var currectElement = fromElement;
while (currectElement && currectElement.isChildOf(toElement.parentElement)) {
let map = getStyle(currectElement);
for (const style in map) {
if (map.hasOwnProperty(style)) {
const value = map[style];
if (!intailStyle[style])
intailStyle[style] = value;
}
}
currectElement = currectElement.parentElement;
}
return intailStyle;
}
const inspect = (e) =>{
const target = e.target;
const results = getInheirtCss(target,editor);
console.log(results)
}
const editor = document.getElementById("editor");
if(editor){
editor.addEventListener("click",inspect)
}
please click
on the text
to get the result