ContentEditable - Get current font color/size

前端 未结 2 692
时光说笑
时光说笑 2021-02-01 08:00

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

2条回答
  •  再見小時候
    2021-02-01 08:37

    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

提交回复
热议问题