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