用js實現「多行溢出隱藏」功能

因爲作移動端比較多,移動端對ellipsis這個css屬性的支持還算不錯,對-webkit-line-clamp的支持不一,特別是安卓機。
查了查資料,發現-webkit-line-clamp並不在css規範中。
那咱們就嘗試手動實現一個,對外暴露接口去調用。css

2種實現思路:html

  • 定義行數,展示該行數之內的文字,隱藏超出行數的文字;
  • 定義總內容的部分,展示該部分,隱藏超出該部分的文字;

實現方式:web

  • 模擬jQuery實現無new構造去調用

須要注意的是,對於文字內容,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)
相關文章
相關標籤/搜索