ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [Javascript] 두 줄이상 말 줄임 (...) 처리
    언어/자바스크립트 2017. 2. 24. 10:42

    두 줄 이상의 말줄임이 필요한 경우 CSS만으로는 처리가 불가능합니다. 따라서 자바스크립트에서 처리를 해줘야 합니다.

    HTML

    <div class="box box--fixed one-line">
      1. Forcing one line regardless
    </div>
    <div class="box box--fixed two-lines">
      2. Forcing two lines of text regardless of overflow
    </div>
    <div class="box box--fixed overflow">
      3. Trying to ellipsis any overflowed content. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.
    </div>
    <div class="box box--fixed overflow">
    4. 이건 테스트다. 글씨가 어떻게 나올지는 나도 모르겠다. 더이상 쓸 말이 없다. 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기 복사 붙여넣기
    </div>
    <div class="box box--responsive">
    5. This is a responsive box that will update it's ellipsis when the screen resizes. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs. This is a responsive box that will update it's ellipsis when the screen resizes.
      The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs. This is a responsive box that will update it's ellipsis when the screen resizes. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped
      over the lazy dogs. This is a responsive box that will update it's ellipsis when the screen resizes. The quick brown fox jumped over the lazy dogs. The quick brown fox jumped over the lazy dogs.
    </div>

    CSS

      body {
       padding: 1%;
     }
     
     .box {
       height: 4.5em;
       background: #eee;
       border: 1px solid #ccc;
       padding: 0.5em 1em;
       margin-right: 30px;
       margin-bottom: 30px;
       overflow: hidden;
       float: left;
     }
     
     .box--fixed {
       width: 140px;
     }
     
     .box--responsive {
       width: 30%;
     }
     /* necessary plugin styles */
     
     .ellip {
       display: block;
       height: 100%;
     }
     
     .ellip-line {
       display: inline-block;
       text-overflow: ellipsis;
       white-space: nowrap;
       word-wrap: normal;
     }
     
     .ellip,
     .ellip-line {
       position: relative;
       overflow: hidden;
       max-width: 100%;
     }
     @media screen and (max-width: 400px) {
       .box--responsive {
         height: 50px;
       }
     }
     
     @media screen and (min-width: 401px) and (max-width: 500px) {
       .box--responsive {
         height: 100px;
       }
     }
     
     @media screen and (min-width: 801px) {
       .box--responsive {
         height: 140px;
       }
     }
     

    JS

    /*!
       * text-overflow: ellipsis;
     */
    (function(factory) {
      'use strict';
      if (typeof define === 'function' && define.amd) {
        define(['jquery'], factory);
      } else {
        factory(jQuery);
      }
    }(function($) {
      'use strict';
      var namespace = 'ellipsis',
        span = '<span style="white-space: nowrap;">',
        defaults = {
          lines: 'auto',
          ellipClass: 'ellip',
          responsive: false
        };
      /**
       * Ellipsis()
       * --------------------------------------------------------------------------
       * @param {Node} el
       * @param {Object} opts
       */
      function Ellipsis(el, opts) {
        var base = this,
          currLine = 0,
          lines = [],
          setStartEllipAt,
          startEllipAt,
          resizeTimer,
          currOffset,
          lineHeight,
          contHeight,
          words;
        base.$cont = $(el);
        base.opts = $.extend({}, defaults, opts);
        function create() {
          base.text = base.$cont.text();
          base.opts.ellipLineClass = base.opts.ellipClass + '-line';
          base.$el = $('<span class="' + base.opts.ellipClass + '" />');
          base.$el.text(base.text);
          base.$cont.empty().append(base.$el);
          init();
        }
        /**
         * init()
         */
        function init() {
          if (typeof base.opts.lines === 'number' && base.opts.lines < 2) {
            base.$el.addClass(base.opts.ellipLineClass);
            return;
          }
          contHeight = base.$cont.height();
          if (base.opts.lines === 'auto' && base.$el.prop('scrollHeight') <= contHeight) {
            return;
          }
          if (!setStartEllipAt) {
            return;
          }
          words = $.trim(base.text).split(/\s+/);
          base.$el.html(span + words.join('</span> ' + span) + '</span>');
          base.$el.find('span').each(setStartEllipAt);
          if (startEllipAt != null) {
            updateText(startEllipAt);
          }
        }
        function updateText(nth) {
          words[nth] = '<span class="' + base.opts.ellipLineClass + '">' + words[nth];
          words.push('</span>');
          base.$el.html(words.join(' '));
        }
        if (base.opts.lines === 'auto') {
          var setStartEllipByHeight = function(i, word) {
            var $word = $(word),
              top = $word.position().top;
            lineHeight = lineHeight || $word.height();
            if (top === currOffset) {
              lines[currLine].push($word);
            } else {
              currOffset = top;
              currLine += 1;
              lines[currLine] = [$word];
            }
            if (top + lineHeight > contHeight) {
              startEllipAt = i - lines[currLine - 1].length;
              return false;
            }
          };
          setStartEllipAt = setStartEllipByHeight;
        }
        if (typeof base.opts.lines === 'number' && base.opts.lines > 1) {
          var setStartEllipByLine = function(i, word) {
            var $word = $(word),
              top = $word.position().top;
            if (top !== currOffset) {
              currOffset = top;
              currLine += 1;
            }
            if (currLine === base.opts.lines) {
              startEllipAt = i;
              return false;
            }
          };
          setStartEllipAt = setStartEllipByLine;
        }
        if (base.opts.responsive) {
          var resize = function() {
            lines = [];
            currLine = 0;
            currOffset = null;
            startEllipAt = null;
            base.$el.html(base.text);
            clearTimeout(resizeTimer);
            resizeTimer = setTimeout(init, 100);
          }
          $(window).on('resize.' + namespace, resize);
        }
        create();
      }
      $.fn[namespace] = function(opts) {
        return this.each(function() {
          try {
            $(this).data(namespace, (new Ellipsis(this, opts)));
          } catch (err) {
            if (window.console) {
              console.error(namespace + ': ' + err);
            }
          }
        });
      };
    }));
    $('.overflow').ellipsis();
    $('.one-line').ellipsis({
      lines: 1
    });
    $('.two-lines').ellipsis({
      lines: 2
    });
    $('.box--responsive').ellipsis({
      responsive: true
    });

    결과


    See the Pen 정적, 반응형 말줄임 by jinhwan (@jinhwan) on CodePen.


    댓글