因爲作移動端比較多,移動端對ellipsis這個css屬性的支持還算不錯,對-webkit-line-clamp的支持不一,特別是安卓機。
查了查資料,發現-webkit-line-clamp並不在css規範中。
那咱們就嘗試手動實現一個,對外暴露接口去調用。css
2種實現思路:html
實現方式:web
須要注意的是,對於文字內容,css中務必設置文字的"行高"這個屬性。this
//調用方式:k('#p').ellipsistoText(3), k('#p').ellipsistoLine(2), k('#p').restoretoLine(), k('#p').restoretoText() (function () { var k = function (selector) { return new F(selector) } var F = function (selector) { this.ele = document.querySelector(selector); if (!this.ele.ori_height) { this.ele.ori_height = this.ele.offsetHeight; //用於保存原始高度 } if (!this.ele.ori_html) { this.ele.ori_html = this.ele.innerHTML; //用於保存原始內容 } } F.prototype = { init: function () { this.ele.style.height = this.ele.ori_height; this.ele.innerHTML = this.ele.ori_html; }, ellipsistoLine: function (l) { this.init(); this.ele.style.cssText = 'overflow: hidden; height: ' + parseInt(window.getComputedStyle(this.ele)['line-height']) * l + 'px'; }, ellipsistoText: function (t) { this.init(); var len = (this.ele.ori_html).length * (1/t); this.ele.innerHTML = this.ele.ori_html.substr(0, len); }, restore: function (){ this.init() } } window.k = k; })(window)