Created
January 23, 2015 19:21
-
-
Save scizers/64de35c0e29b33b238ca to your computer and use it in GitHub Desktop.
autofit text angaularjs directive
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
app.directive('autofit', function(){ | |
return function(scope, element, attrs){ | |
var span = element.find('span:visible:first'); | |
var maxHeight = element.height(); | |
var maxWidth = element.width(); | |
var originalFontSize = parseInt(element.css('font-size').replace('px',''),10); | |
function resize(){ | |
var fontSize = originalFontSize; | |
var textHeight = span.height(); | |
var textWidth = span.width(); | |
do { | |
element.css('font-size', fontSize + 'px'); | |
//span.css('line-height', fontSize + 'px'); | |
element.css('line-height', fontSize + 'px'); | |
textHeight = span.height(); | |
textWidth = span.width(); | |
fontSize--; | |
} while ((textHeight > maxHeight || textWidth > maxWidth) && fontSize > 3); | |
} | |
if(attrs.autofit){ | |
var parts = attrs.autofit.split(','); | |
for(var i in parts){ | |
scope.$watch(parts[i], function(){ | |
resize(); | |
}); | |
} | |
} | |
resize(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment