English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
先前用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
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]);+"..."; } } }
Here we use getElementsByTagName to get all nodes, traverse them, and filter nodes containing the custom attribute 'limit', then get the value of the custom attribute 'limit' of each node, put it into the limit array, put the text of each node into the Text array, compare the value to be truncated with the text length, and perform truncation.
All JS, here written to be called automatically:
<script type="text/javascript"> window.onload=function(){ (function limit(){ 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]);+"..."; } } } }()); } </script>
Illustration:
That's all for this article. I hope it will be helpful to everyone's learning and I also hope everyone will support the Yelling Tutorial more.
Statement: The content of this article is from the Internet, and the copyright belongs to the original author. The content is contributed and uploaded by Internet users spontaneously. This website does not own the copyright, has not been manually edited, and does not assume any relevant legal liability. If you find any copyright-infringing content, please send an email to: notice#oldtoolbag.com (When reporting, please replace # with @ and provide relevant evidence. Once verified, this site will immediately delete the infringing content.)