Home >Web Front-end >JS Tutorial >How to implement text width and height adaptive div
Here I would like to share with you an article on how to implement text width and height adaptive div. Friends in need can refer to it.
After trying several JavaScript snippets and libraries for fitting text into divs, I'm a little torn as none of these handle the "height" of the DIV and the text may overflow.. ....
So I wrote this simple function in CoffeeScript that tests if the text overflows the div and it will reduce its size until it fits!
The function finds elements marked with the .Resig class and resizes only them.
autoSizeText = -> elements = $('.resize') console.log elements return if elements.length < 0 for el in elements do (el) -> resizeText = -> elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px' $(el).css('font-size', elNewFontSize) resizeText() while el.scrollHeight > el.offsetHeight
This is the JavaScript compiled version:
var autoSizeText;autoSizeText = function() { var el, elements, _i, _len, _results; elements = $('.resize'); console.log(elements); if (elements.length < 0) { return; } _results = []; for (_i = 0, _len = elements.length; _i < _len; _i++) { el = elements[_i]; _results.push((function(el) { var resizeText, _results1; resizeText = function() { var elNewFontSize; elNewFontSize = (parseInt($(el).css('font-size').slice(0, -2)) - 1) + 'px'; return $(el).css('font-size', elNewFontSize); }; _results1 = []; while (el.scrollHeight > el.offsetHeight) { _results1.push(resizeText()); } return _results1; })(el)); } return _results;};
The above is the detailed content of How to implement text width and height adaptive div. For more information, please follow other related articles on the PHP Chinese website!