ZH奶酪:HTML元素文本溢出顯示省略號(...)

一 單行文本

overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;

overflow 屬性規定當內容溢出元素框時發生的事情。css

visible 默認值。內容不會被修剪,會呈如今元素框以外。
hidden 內容會被修剪,而且其他內容是不可見的。
scroll 內容會被修剪,可是瀏覽器會顯示滾動條以便查看其他的內容。
auto 若是內容被修剪,則瀏覽器會顯示滾動條以便查看其他的內容。
inherit 規定應該從父元素繼承 overflow 屬性的值。

  

 

 

 

 

text-overflow 屬性規定當文本溢出包含元素時發生的事情。node

clip:修剪文本;git

ellipsis:顯示省略號來表明被修剪的文本;github

string:使用給定的字符串來表明被修剪的文本;web

white-space 屬性設置如何處理元素內的空白。api

normal 默認。空白會被瀏覽器忽略。
pre 空白會被瀏覽器保留。其行爲方式相似 HTML 中的 <pre> 標籤。
nowrap 文本不會換行,文本會在在同一行上繼續,直到遇到 <br> 標籤爲止。
pre-wrap 保留空白符序列,可是正常地進行換行。
pre-line 合併空白符序列,可是保留換行符。
inherit 規定應該從父元素繼承 white-space 屬性的值。

 

 

 

 

 

 

二 多行文本,提供了幾種方法,效果圖中的每一段文字對應一個方法:

HTML代碼瀏覽器

<h1>Line Clampin'</h1>

<h2>Weird WebKit Flexbox Way</h2>
<div class="module line-clamp">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

<h2>Fade Out Way</h2>
<div class="module fade">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

<h2>Opera Overflow Way</h2>
<div class="module last-line">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

<h2>Clamp.js Way</h2>
<div class="module js">
  <p id="clampjs">Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

<h2>ftellipsis Way</h2>
<div class="module js ftellipsis" id="ftellipsis">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>

<h2>TextOverflowClamp.js Way</h2>
<div class="module js textoverflowclamp" id="textoverflowclamp">
  <p>Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Vestibulum tortor quam, feugiat vitae, ultricies eget, tempor sit amet, ante. Donec eu libero sit amet quam egestas semper. Aenean ultricies mi vitae est. Mauris placerat eleifend leo.</p>
</div>
View Code

CSS代碼app

@import url(http://fonts.googleapis.com/css?family=Open+Sans);

body {
  padding: 20px;
  font: 1.2em/1.2em 'Open Sans', sans-serif;
}
.module {
  width: 250px;
  margin: 0 0 1em 0;
  overflow: hidden;
}
.module p {
  margin: 0;
}

.line-clamp {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  -webkit-box-orient: vertical;  
}

.fade {
  position: relative;
  height: 3.6em; /* exactly three lines */
}
.fade:after {
  content: "";
  text-align: right;
  position: absolute;
  bottom: 0;
  right: 0;
  width: 70%;
  height: 1.2em;
  background: linear-gradient(to right, rgba(255, 255, 255, 0), rgba(255, 255, 255, 1) 50%);
}

.last-line {
  height: 3.6em; /* exactly three lines */
  text-overflow: -o-ellipsis-lastline;
}

.ftellipsis {
  height: 3.6em;
}

h1 {
  margin: 0 0 1em 0;
}
h2 {
  font-size: 1.2em;
}
View Code

JS代碼ide

// https://github.com/josephschmitt/Clamp.js
var module = document.getElementById("clampjs");
$clamp(module, {clamp: 2});

// https://github.com/ftlabs/ftellipsis
var element = document.getElementById('ftellipsis');
var ellipsis = new Ellipsis(element);

ellipsis.calc();
ellipsis.set();






// http://codepen.io/Merri/pen/Dsuim
/**
  * TextOverflowClamp.js
  *
  * Updated 2013-05-09 to remove jQuery dependancy.
  * But be careful with webfonts!
  */

// bind function support for older browsers without it
// https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Function/bind
if (!Function.prototype.bind) {
  Function.prototype.bind = function (oThis) {
    if (typeof this !== "function") {
      // closest thing possible to the ECMAScript 5 internal IsCallable function
      throw new TypeError("Function.prototype.bind - what is trying to be bound is not callable");
    }
 
    var aArgs = Array.prototype.slice.call(arguments, 1),
        fToBind = this,
        fNOP = function () {},
        fBound = function () {
          return fToBind.apply(this instanceof fNOP && oThis
                                 ? this
                                 : oThis,
                               aArgs.concat(Array.prototype.slice.call(arguments)));
        };
 
    fNOP.prototype = this.prototype;
    fBound.prototype = new fNOP();
 
    return fBound;
  };
}

// the actual meat is here
(function(w, d){
    var clamp, measure, text, lineWidth,
        lineStart, lineCount, wordStart,
        line, lineText, wasNewLine,
    ce = d.createElement.bind(d),
    ctn = d.createTextNode.bind(d);
    
    // measurement element is made a child of the clamped element to get it's style
    measure = ce('span');
  
    (function(s){
        s.position = 'absolute'; // prevent page reflow
        s.whiteSpace = 'pre'; // cross-browser width results
        s.visibility = 'hidden'; // prevent drawing
    })(measure.style);
    
    clamp = function (el, lineClamp) {
    // make sure the element belongs to the document
    if(!el.ownerDocument || !el.ownerDocument === d) return;
        // reset to safe starting values
        lineStart = wordStart = 0;
        lineCount = 1;
        wasNewLine = false; 
        lineWidth = el.clientWidth;
        // get all the text, remove any line changes
        text = (el.textContent || el.innerText).replace(/\n/g, ' ');
        // remove all content
        while(el.firstChild !== null)
            el.removeChild(el.firstChild);
        // add measurement element within so it inherits styles
        el.appendChild(measure);
        // http://ejohn.org/blog/search-and-dont-replace/
        text.replace(/ /g, function(m, pos) {
            // ignore any further processing if we have total lines
      if(lineCount === lineClamp) return;
            // create a text node and place it in the measurement element
            measure.appendChild(ctn(text.substr(lineStart, pos - lineStart)));
            // have we exceeded allowed line width?
            if(lineWidth < measure.clientWidth) {
                if(wasNewLine) {
                    // we have a long word so it gets a line of it's own
                    lineText = text.substr(lineStart, pos + 1 - lineStart);
                    // next line start position
                    lineStart = pos + 1;
                } else {
                    // grab the text until this word
                    lineText = text.substr(lineStart, wordStart - lineStart);
                    // next line start position
                    lineStart = wordStart;
                }
                // create a line element
                line = ce('span');
                // add text to the line element
                line.appendChild(ctn(lineText));
                // add the line element to the container
                el.appendChild(line);
                // yes, we created a new line
                wasNewLine = true;
        lineCount++;
            } else {
                // did not create a new line
                wasNewLine = false;
            }
            // remember last word start position
            wordStart = pos + 1;
            // clear measurement element
            measure.removeChild(measure.firstChild);
        });
        // remove the measurement element from the container
        el.removeChild(measure);
        // create the last line element
        line = ce('span');
        // give styles required for text-overflow to kick in
        (function(s){
            s.display = 'inline-block';
            s.overflow = 'hidden';
            s.textOverflow = 'ellipsis';
            s.whiteSpace = 'nowrap';
            s.width = '100%';
        })(line.style);
        // add all remaining text to the line element
        line.appendChild(ctn(text.substr(lineStart)));
        // add the line element to the container
        el.appendChild(line);
    }
    w.clamp = clamp;
})(window, document);

// the only bit of jQuery
$(window).bind('load', function() {
  clamp(document.getElementById('textoverflowclamp'), 3);
});
View Code

其中ui

(1)-webkit-line-clamp 這種方法指支持部分瀏覽器,並且要與其餘兩個屬性同時使用:

.line-clamp {
display: -webkit-box;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
}

(2)clamp.js 下載地址及使用方法:https://github.com/josephschmitt/Clamp.js

(3)ftellipsis 下載地址及使用方法:https://github.com/ftlabs/ftellipsis

(4)jQuery.dotdotdot 下載地址及使用方法:https://github.com/BeSite/jQuery.dotdotdot

參考文章:

[1] https://css-tricks.com/line-clampin/

[2] http://www.css88.com/archives/5206

[3] http://codepen.io/Merri/pen/Dsuim

[4] http://codepen.io/feiwen8772/pen/AckqK

相關文章
相關標籤/搜索