Skip to content

Instantly share code, notes, and snippets.

@auser
Created March 6, 2014 03:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save auser/9381634 to your computer and use it in GitHub Desktop.
Save auser/9381634 to your computer and use it in GitHub Desktop.
function difference(a, b) {
var out = {};
if (!a || !b) return out;
for (var key in a) {
if (b.hasOwnProperty(key) && typeof(b[key]) !== "undefined") {
if (a[key] !== b[key]) {
console.log('difference', a[key], '|', b[key]);
out[key] = a[key];
}
}
}
return out;
}
var styleObject = function(ele) {
this.rootElement = ele;
this.rootRules = this.getStyleObject(ele);
}
styleObject.prototype.getElementStyles = function(element) {
return window.getComputedStyle(element, null);
}
styleObject.prototype.getStyleObject = function(element) {
var obj = {},
numFormat = /\D/g;
var dcl = this.getElementStyles(element);
for (var prop in dcl) {
if (numFormat.test(prop) && typeof(dcl[prop]) !== "object" &&
typeof(dcl[prop]) !== "function" &&
prop !== "cssText" &&
prop !== "length" &&
dcl[prop].length > 0
) {
obj[prop] = dcl[prop];
}
}
return obj;
}
styleObject.prototype.applyToElements = function() {
this.childApplyToElements(this.rootElement);
}
styleObject.prototype.childApplyToElements = function(parent) {
for (var i = 0; i < parent.children.length; i++) {
var child = parent.children[i];
this.childApplyToElements(child);
};
this.applyToElement(parent);
}
styleObject.prototype.applyToElement = function(element) {
var self = this;
function dumpComputedStyles(elem) {
var allStyles = [];
var csObj = self.getElementStyles(elem);
var diff;
if (element === self.rootElement) {
diff = self.rootRules;
} else {
diff = difference(csObj, self.rootRules);
}
console.log('diff', diff, element === self.rootElement);
var len = diff.length;
console.log('difffffff------------------>', diff);
for (var prop in diff) {
allStyles.push(prop+":"+diff[prop]);
}
// Finally, copy the element styles
if (element.style) {
allStyles.push(element.style.cssText);
}
return allStyles;
}
var allStyles = dumpComputedStyles(element)
element.setAttribute('style', allStyles.join(';'));
}
var ele = document.getElementById('header');
var so = new styleObject(ele);
so.applyToElements();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment