Created
March 6, 2014 03:18
-
-
Save auser/9381634 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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