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

How to implement text width and height adaptive div

不言
Release: 2018-11-06 14:42:02
Original
2603 people have browsed it

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
Copy after login

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;};
Copy after login

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!

Related labels:
div
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template