Created
August 18, 2014 00:42
-
-
Save leocaseiro/e3e1277e68733c68328e to your computer and use it in GitHub Desktop.
This file contains hidden or 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($) { | |
if ($.fn.style) { | |
return; | |
} | |
// Escape regex chars with \ | |
var escape = function(text) { | |
return text.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"); | |
}; | |
// For those who need them (< IE 9), add support for CSS functions | |
var isStyleFuncSupported = !!CSSStyleDeclaration.prototype.getPropertyValue; | |
if (!isStyleFuncSupported) { | |
CSSStyleDeclaration.prototype.getPropertyValue = function(a) { | |
return this.getAttribute(a); | |
}; | |
CSSStyleDeclaration.prototype.setProperty = function(styleName, value, priority) { | |
this.setAttribute(styleName, value); | |
var priority = typeof priority != 'undefined' ? priority : ''; | |
if (priority != '') { | |
// Add priority manually | |
var rule = new RegExp(escape(styleName) + '\\s*:\\s*' + escape(value) + | |
'(\\s*;)?', 'gmi'); | |
this.cssText = | |
this.cssText.replace(rule, styleName + ': ' + value + ' !' + priority + ';'); | |
} | |
}; | |
CSSStyleDeclaration.prototype.removeProperty = function(a) { | |
return this.removeAttribute(a); | |
}; | |
CSSStyleDeclaration.prototype.getPropertyPriority = function(styleName) { | |
var rule = new RegExp(escape(styleName) + '\\s*:\\s*[^\\s]*\\s*!important(\\s*;)?', | |
'gmi'); | |
return rule.test(this.cssText) ? 'important' : ''; | |
} | |
} | |
// The style function | |
$.fn.style = function(styleName, value, priority) { | |
// DOM node | |
var node = this.get(0); | |
// Ensure we have a DOM node | |
if (typeof node == 'undefined') { | |
return this; | |
} | |
// CSSStyleDeclaration | |
var style = this.get(0).style; | |
// Getter/Setter | |
if (typeof styleName != 'undefined') { | |
if (typeof value != 'undefined') { | |
// Set style property | |
priority = typeof priority != 'undefined' ? priority : ''; | |
style.setProperty(styleName, value, priority); | |
return this; | |
} else { | |
// Get style property | |
return style.getPropertyValue(styleName); | |
} | |
} else { | |
// Get CSSStyleDeclaration | |
return style; | |
} | |
}; | |
})(jQuery); | |
/** | |
* Usage: | |
* $('div').style('background-position', '-20px 0', 'important'); | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment