Duplicating an element (and its style) with JavaScript

后端 未结 3 697
天命终不由人
天命终不由人 2020-12-13 13:39

For a JavaScript library I\'m implementing, I need to clone an element which has exactly the same applied style than the original one. Although I\'ve gained

3条回答
  •  不知归路
    2020-12-13 14:18

    After looking at a couple of good solutions across the WEB, I decided to combine all the best aspects of each and come up with this.

    I left my solution in plain super fast Javascript, so that everybody can translate to their latest and great JS flavour of the month.

    Representing the vanilla from manilla.....


     * @problem: Sometimes .cloneNode(true) doesn't copy the styles and your are left
     * with everything copied but no styling applied to the clonedNode (it looks plain / ugly). Solution:
     * 
     * @solution: call synchronizeCssStyles to copy styles from source (src) element to
     * destination (dest) element.
     * 
     * @author: Luigi D'Amico (www.8bitplatoon.com)
     * 
     */
    function synchronizeCssStyles(src, destination, recursively) {
    
        // if recursively = true, then we assume the src dom structure and destination dom structure are identical (ie: cloneNode was used)
    
        // window.getComputedStyle vs document.defaultView.getComputedStyle 
        // @TBD: also check for compatibility on IE/Edge 
        destination.style.cssText = document.defaultView.getComputedStyle(src, "").cssText;
    
        if (recursively) {
            var vSrcElements = src.getElementsByTagName("*");
            var vDstElements = destination.getElementsByTagName("*");
    
            for (var i = vSrcElements.length; i--;) {
                var vSrcElement = vSrcElements[i];
                var vDstElement = vDstElements[i];
    //          console.log(i + " >> " + vSrcElement + " :: " + vDstElement);
                vDstElement.style.cssText = document.defaultView.getComputedStyle(vSrcElement, "").cssText;
            }
        }
    }
    

提交回复
热议问题