js实现文字截断功能

2022-01-14站长百科56413

这篇文章主要为大家详细介绍了js代码如何实现文字截断功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

先前用jq做了一个文字截断功能,但是不用jq的项目要实现此功能还要引如jq显得过于麻烦。这里写了一个js的文字截断功能。直接上代码。 

HTML(测试用的): 

 我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox我是pox

JS: 

 var limit=[]; var Text=[]; var Pox=document.getElementsByTagName('*'); for(var i=0;i<Pox.length;i++){ if(Pox[i].getAttribute("limit")){ limit[i]=Pox[i].getAttribute("limit"); Text[i]=Pox[i].innerHTML; if(limit[i]<Text[i].length){ Pox[i].innerHTML=Text[i].substring(0,limit[i])+"..."; } } } 

这里用getElementsByTagName获取所有节点遍历,if(Pox[i].getAttribute("limit"))筛选含有limit这个自定义属性的节点,然后获取各个节点自定义属性limit的值,将其放入limit数组中,把各个节点文字放入Text数组中,将需要截断的值和文本长度作比较,进行截断。 

全部JS,这里写的自调:

 

效果图:

以上就是js实现文字截断功能的详细内容,更多请关注本站其它相关文章!

本文地址:https://www.ufcn.cn/article/540290.html

如非特殊说明,本站内容均来自于网友自主分享,概不代表本站观点,如有任何问题我们都将在收到反馈后的第一时间进行处理!