这篇文章主要介绍了关于如何使用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中文网!
相关推荐:
以上就是如何使用js来实现多行溢出隐藏功能的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号