如何使用js来实现多行溢出隐藏功能

不言
不言 原创
2018-07-14 11:06:32 1779浏览

这篇文章主要介绍了关于如何使用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核实处理。