Created
May 19, 2010 06:10
-
-
Save stilist/406015 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
// Sometimes you want to know the exact pixel dimension of a CSS property, but it’s | |
// in non-pixel units. This hack might help you out. | |
// | |
// Note: assumes a jQuery object `$`. | |
// | |
// License: http://github.com/stilist/ratafiacurrant/blob/master/License | |
var cssDimensionInPx = (function () { | |
return function ($element, property) { | |
var dimension = $element.css(property); | |
var dimensionInt = parseInt(dimension, 10); | |
var fontSize = parseInt($element.css("font-size"), 10); | |
if (dimension && !isNaN(dimensionInt)) { | |
// no unit | |
if ("" + dimensionInt === dimension) { | |
return dimensionInt; | |
// px | |
} else if (dimension.length - 2 === dimension.indexOf("px")) { | |
return dimensionInt; | |
// em | |
} else if (dimension.length - 2 === dimension.indexOf("em")) { | |
return dimensionInt * fontSize; | |
// % | |
} else if (dimension.length - 1 === dimension.indexOf("%")) { | |
return (dimensionInt * 0.01) * fontSize; | |
} | |
} else { | |
return 0; | |
} | |
}; | |
})(); | |
alert(cssDimensionInPx($("body"), "width")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment