Copy all styles from one element to another

后端 未结 3 1838
臣服心动
臣服心动 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

    If you don't care about IE, then you can do this:

    var p = document.getElementById("your_p_id");
    var div = document.createElement("div");
    div.innerHTML = "your div content";
    div.style.cssText = document.defaultView.getComputedStyle(p, "").cssText;
    #your_p_id {
      color: #123124;
      background-color: #decbda;
    }
    <textArea id="your_p_id">Hello world!</textArea>

    This works for inline, embedded, and inherited styles.

    EDIT: And by "don't care about IE," I of course meant "don't care about anything except Webkit."

    UPDATE: This works in the current versions of Chrome(19), Safari(5), Firefox(12), and IE(9). It also works in older versions of some, such as IE8.

    0 讨论(0)
  • 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
    }
    
    0 讨论(0)
  • 2020-12-14 06:17

    Try to copy every CSS-properties like this:

    $("#target").css("border", $("#source").css("border"));
    $("#target").css("background", $("#source").css("background"));
    #source {
      background-color: #dfeacb !important;
      color: #bbae4e !important;
      border: 1px solid green !important;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <textArea id="source">Hello world!</textArea>
    <textArea id="target">Hello world!</textArea>

    Why not? you can create the dictionary that may consists of all properties.

    0 讨论(0)
提交回复
热议问题