Copy all styles from one element to another

后端 未结 3 1846
臣服心动
臣服心动 2020-12-14 05:49

How can i get every styles (even inherited) from an element A to an element B ? in javascript or using jquery.

let\'s tell i have an element

3条回答
  •  误落风尘
    2020-12-14 06:12

    Actually, sdleihssirhc's answer will not work on firefox as getComputedStyle(p, "").cssText will return an empty string, it's a longstanding and know bug: https://bugzilla.mozilla.org/show_bug.cgi?id=137687

    The solution to also support Firefox is to iterate on getComputedStyle properties and create the CSS string manually:

    var clonedNode = document.createElement("div");
    const styles = window.getComputedStyle(node);
    if (styles.cssText !== '') {
        clonedNode.style.cssText = styles.cssText;
    } else {
        const cssText = Object.values(styles).reduce(
            (css, propertyName) =>
                `${css}${propertyName}:${styles.getPropertyValue(
                    propertyName
                )};`
        );
    
        clonedNode.style.cssText = cssText
    }
    

提交回复
热议问题