Подтвердить что ты не робот

Установить/Скопировать javascript-стиль из одного элемента в другой

Поэтому я пытаюсь скопировать все стили, которые применяются к одному элементу (class/id/tagName/attribute и т.д.). До сих пор я узнал, что могу скопировать вычисленный стиль элемента, только одна проблема... можно применить его к внешнему элементу; /

или другой способ скопировать весь стиль.

(это насколько я понял:/) http://jsfiddle.net/8KdJd/2/

   //queriks mode + minor changes to retrive the computed style
function getCS(el)
{
    if (el.currentStyle)
        var y = el.currentStyle;
    else if (window.getComputedStyle)
        var y = document.defaultView.getComputedStyle(el,null);
    return y;
}
function setCS(el,cs)
{
    if (el.currentStyle)
    {

        el.currentStyle = cs;
        el.style = cs;
    }
    else if (window.getComputedStyle)
    {el.style = cs 
    }

}


var myLink = document.getElementById('myLink');
var anotherLink = document.getElementById('anotherLink');

var CS_myLink = getCS(myLink);
setCS(anotherLink,CS_myLink);
4b9b3361

Ответ 1

Обновление: как предложено @icl7126, вот более короткая версия для практически такого же использования. Хорошо помнить, что этот код не будет работать в большинстве/старых браузерах, если не будет предварительно скомпилирован.

Оригинал (ES 2017):

function copyNodeStyle(sourceNode, targetNode) {
  const computedStyle = window.getComputedStyle(sourceNode);
  Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}

Предварительно скомпилировано (ES 5):

function copyNodeStyle(sourceNode, targetNode) {
  var computedStyle = window.getComputedStyle(sourceNode);
  Array.from(computedStyle).forEach(function (key) {
    return targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key));
  });
}
#

Оригинальный ответ опубликован в ноябре 13 года. Переменные CSS не поддерживались тогда. (первое знакомство с Firefox в июле 2014 г.)

#

Это оно! Я понял :)

Я видел, что многие люди видят этот вопрос, поэтому ниже приведен более подробный и понятный код.

var copyComputedStyle = function(from,to){
    var computed_style_object = false;
    //trying to figure out which style object we need to use depense on the browser support
    //so we try until we have one
    computed_style_object = from.currentStyle || document.defaultView.getComputedStyle(from,null);

    //if the browser dose not support both methods we will return null
    if(!computed_style_object) return null;

        var stylePropertyValid = function(name,value){
                    //checking that the value is not a undefined
            return typeof value !== 'undefined' &&
                    //checking that the value is not a object
                    typeof value !== 'object' &&
                    //checking that the value is not a function
                    typeof value !== 'function' &&
                    //checking that we dosent have empty string
                    value.length > 0 &&
                    //checking that the property is not int index ( happens on some browser
                    value != parseInt(value)

        };

    //we iterating the computed style object and compy the style props and the values 
    for(property in computed_style_object)
    {
        //checking if the property and value we get are valid sinse browser have different implementations
            if(stylePropertyValid(property,computed_style_object[property]))
            {
                //applying the style property to the target element
                    to.style[property] = computed_style_object[property];

            }   
    }   

};

Ответ 2

Немного более короткое решение с использованием setProperty, getPropertyValue и getPropertyPriority.

function copyNodeStyle(sourceNode, targetNode) {
  const computedStyle = window.getComputedStyle(sourceNode);
  Array.from(computedStyle).forEach(key => targetNode.style.setProperty(key, computedStyle.getPropertyValue(key), computedStyle.getPropertyPriority(key)))
}

Полезные документы MDN: getComputedStyle и CSSStyleDeclaration