У меня есть набор блоков фиксированной высоты , содержащих текст. Ширина поля указана в процентах.

Текст усекается с помощью этого фрагмента jquery.

(function($) {
  $.fn.noOverflow = function(ellipsis) {
    if (typeof ellipsis === 'undefined') {
      ellipsis = '';
    }
    return this.each(function() {
      var el = $(this);
      if (typeof this.overflow_text === 'undefined') {
        // store initial text as a property of the current element
        // in order to reuse it if the container is resized
        this.overflow_text = {
          originalText: el.text()
        }
      }
      // create a hidden "puppet" for better user experience
      var t = $(this.cloneNode(true)).hide().css({
        'position': 'absolute',
        'width': 'auto',
        'height': 'auto',
        'overflow': 'visible',
        'max-width': 'inherit',
        'max-height': 'inherit'
      });
      el.after(t);
      var text = this.overflow_text.originalText;
      t.text(text + "");
      // use the puppet to try for the proper text length, removing characters one by one
      // until the puppet will be of designed size
      while (text.length > 0 && (t.width() > el.width() || t.height() > el.height())) {
        text = text.substr(0, text.length - 1);
        t.text(text + ellipsis);
      }
      el.text(t.text());
      // get rid of the puppet
      t.remove();
    });

  };
})(jQuery);

function updateCutoff() {
  $('.txt').noOverflow('...');
}
updateCutoff();
$(window).resize(updateCutoff);
body {
  font-family: Arial, sans-serif;
}
.wrapper {
  border: 2px solid #000;
  width: 25%;
  box-sizing: border-box;
  float: left;
}
.txt {
  font-size: 12px;
  line-height: 1.25;
  display: block;
  overflow: hidden;
  height: 3.75em;
}
@media only screen and (max-width: 767px) {
  .wrapper {
    width: 50%;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur</span>
</div>

<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit fugiat</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur est laborum.</span>
</div>

Проблема в том, что текст не занимает всю высоту полей, даже если текста для этого достаточно. Текст остается на одной строке .

Почему это происходит?

1
Razvan Zamfir 23 Окт 2018 в 12:31

2 ответа

Лучший ответ

Проблема в этом фрагменте кода t.width() > el.width(). Он учитывает ширину только один раз, однако, если у вас несколько линий, вам нужно будет учитывать все линии. Следовательно, вам нужно будет исправить эту часть.

В целях иллюстрации я изменил его на t.width() > 3 * el.width()

(function($) {
  $.fn.noOverflow = function(ellipsis) {
    if (typeof ellipsis === 'undefined') {
      ellipsis = '';
    }
    return this.each(function() {
      var el = $(this);
      if (typeof this.overflow_text === 'undefined') {
        // store initial text as a property of the current element
        // in order to reuse it if the container is resized
        this.overflow_text = {
          originalText: el.text()
        }
      }
      // create a hidden "puppet" for better user experience
      var t = $(this.cloneNode(true)).hide().css({
        'position': 'absolute',
        'width': 'auto',
        'height': 'auto',
        'overflow': 'visible',
        'max-width': 'inherit',
        'max-height': 'inherit'
      });
      el.after(t);
      var text = this.overflow_text.originalText;
      t.text(text + "");
      // use the puppet to try for the proper text length, removing characters one by one
      // until the puppet will be of designed size
      while (text.length > 0 && (t.width() > 3 * el.width() || t.height() > el.height())) {
        text = text.substr(0, text.length - 1);
        t.text(text + ellipsis);
      }
      el.text(t.text());
      // get rid of the puppet
      t.remove();
    });

  };
})(jQuery);

function updateCutoff() {
  $('.txt').noOverflow('...');
}
updateCutoff();
$(window).resize(updateCutoff);
body {
  font-family: Arial, sans-serif;
}
.wrapper {
  border: 2px solid #000;
  width: 25%;
  box-sizing: border-box;
  float: left;
}
.txt {
  font-size: 12px;
  line-height: 1.25;
  display: block;
  overflow: hidden;
  height: 3.75em;
}
@media only screen and (max-width: 767px) {
  .wrapper {
    width: 50%;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur</span>
</div>

<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit fugiat</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur est laborum.</span>
</div>
0
Nikhil Aggarwal 23 Окт 2018 в 09:39

Изменить условие while (text.length > 0 && (t.width() < el.width() || t.height() >= el.height()))

(function($) {
  $.fn.noOverflow = function(ellipsis) {
    if (typeof ellipsis === 'undefined') {
      ellipsis = '';
    }
    return this.each(function() {
      var el = $(this);
      if (typeof this.overflow_text === 'undefined') {
        // store initial text as a property of the current element
        // in order to reuse it if the container is resized
        this.overflow_text = {
          originalText: el.text()
        }
      }
      // create a hidden "puppet" for better user experience
      var t = $(this.cloneNode(true)).hide().css({
        'position': 'absolute',
        'width': 'auto',
        'height': 'auto',
        'overflow': 'visible',
        'max-width': 'inherit',
        'max-height': 'inherit'
      });
      el.after(t);
      var text = this.overflow_text.originalText;
      t.text(text + "");
      // use the puppet to try for the proper text length, removing characters one by one
      // until the puppet will be of designed size
      while (text.length > 0 && (t.width() < el.width() || t.height() >= el.height())) {
        text = text.substr(0, text.length - 1);
        t.text(text + ellipsis);
      }
      el.text(t.text());
      // get rid of the puppet
      t.remove();
    });

  };
})(jQuery);

function updateCutoff() {
  $('.txt').noOverflow('...');
}
updateCutoff();
$(window).resize(updateCutoff);
body {
  font-family: Arial, sans-serif;
}
.wrapper {
  border: 2px solid #000;
  width: 25%;
  box-sizing: border-box;
  float: left;
}
.txt {
  font-size: 12px;
  line-height: 1.25;
  display: block;
  overflow: hidden;
  height: 3.75em;
}
@media only screen and (max-width: 767px) {
  .wrapper {
    width: 50%;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur</span>
</div>

<div class="wrapper">
  <span class="txt">Lorem ipsum dolor sit amet, consectetur adipisicing elit fugiat</span>
</div>

<div class="wrapper">
  <span class="txt">Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur est laborum .</span>
</div>
0
Sooriya Dasanayake 23 Окт 2018 в 10:07
52945703