您好,欢迎访问一九零五行业门户网

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

这篇文章主要介绍了关于如何使用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)
以上就是本文的全部内容,希望对大家的学习有所帮助,更多相关内容请关注!
相关推荐:
使用javascript控制台如何改进工作的流程
如何使用原生js来实现ajax
对于js的事件冒泡和事件捕获的分析
以上就是如何使用js来实现多行溢出隐藏功能的详细内容。
其它类似信息

推荐信息