Home  >  Article  >  Web Front-end  >  How to implement text width and height adaptive div

How to implement text width and height adaptive div

不言
不言Original
2018-11-06 14:42:022497browse

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(&#39;font-size&#39;).slice(0, -2)) - 1) + &#39;px&#39;
          $(el).css(&#39;font-size&#39;, elNewFontSize)

        resizeText() while el.scrollHeight > el.offsetHeight

This is the JavaScript compiled version:

var autoSizeText;autoSizeText = function() {
  var el, elements, _i, _len, _results;
  elements = $(&#39;.resize&#39;);
  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(&#39;font-size&#39;).slice(0, -2)) - 1) + &#39;px&#39;;
        return $(el).css(&#39;font-size&#39;, 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn