Duplicating an element (and its style) with JavaScript

后端 未结 3 694
天命终不由人
天命终不由人 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

    None of those worked for me, but I came up with this based on Luigi's answer.

    copyStyles(source: HTMLElement, destination: HTMLElement) {
    
        // Get a list of all the source and destination elements
        const srcElements = >source.getElementsByTagName('*');
        const dstElements = >destination.getElementsByTagName('*');
    
        // For each element
        for (let i = srcElements.length; i--;) {
            const srcElement = srcElements[i];
            const dstElement = dstElements[i];
            const sourceElementStyles = document.defaultView.getComputedStyle(srcElement, '');
            const styleAttributeKeyNumbers = Object.keys(sourceElementStyles);
    
            // Copy the attribute
            for (let j = 0; j < styleAttributeKeyNumbers.length; j++) {
                const attributeKeyNumber = styleAttributeKeyNumbers[j];
                const attributeKey: string = sourceElementStyles[attributeKeyNumber];
                dstElement.style[attributeKey] = sourceElementStyles[attributeKey];
            }
        }
    }
    

提交回复
热议问题