首頁  >  文章  >  web前端  >  如何使用js來實現多行溢出隱藏功能

如何使用js來實現多行溢出隱藏功能

不言
不言原創
2018-07-14 11:06:322176瀏覽

這篇文章主要介紹了關於如何使用js來實現多行溢出隱藏功能,有著一定的參考價值,現在分享給大家,有需要的朋友可以參考一下

由於做行動端比較多,行動端對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)

以上就是本文的全部內容,希望對大家的學習有所幫助,更多相關內容請關注PHP中文網!

相關推薦:

使用JavaScript控制台如何改進工作的流程

如何使用原生js來實作Ajax

對於js的事件冒泡與事件擷取的分析

#

以上是如何使用js來實現多行溢出隱藏功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn