由于做移動端比較多,移動端對ellipsis這個css屬性的支持還算不錯,對-webkit-line-clamp的支持不一,特別是安卓機。
查了查資料,發(fā)現(xiàn)-webkit-line-clamp并不在css規(guī)范中。
那我們就嘗試手動實現(xiàn)一個,對外暴露接口去調(diào)用。
2種實現(xiàn)思路:
定義行數(shù),展現(xiàn)該行數(shù)以內(nèi)的文字,隱藏超出行數(shù)的文字;
定義總內(nèi)容的部分,展現(xiàn)該部分,隱藏超出該部分的文字;
實現(xiàn)方式:
模擬jQuery實現(xiàn)無new構(gòu)造去調(diào)用
需要注意的是,對于文字內(nèi)容,css中務(wù)必設(shè)置文字的"行高"這個屬性。
//調(diào)用方式: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; //用于保存原始內(nèi)容 } } 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); }, restoretoLine: function () { this.ele.style.height = this.ele.ori_height + 'px'; }, restoretoText: function () { this.ele.innerHTML = this.ele.ori_html; } } window.k = k; })(window)
聲明:本網(wǎng)頁內(nèi)容旨在傳播知識,若有侵權(quán)等問題請及時與本網(wǎng)聯(lián)系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com