27th
MAY

js控制下拉框里超过文字变成省略号

Posted by 可乐 under 网页设计

我们先建个测试页面,看看加长效果是如何的

效果图:

  1. < !DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
  2. <html xmlns="http://www.w3.org/1999/xhtml">
  3. <head>
  4. <meta http-equiv="Content-Type" content="text/html; charset=gb1231" />
  5. <title>测试</title>
  6. </head>
  7. <body>
  8.     <select id="a">
  9.         <option>下拉框里的字太多了,下拉框会变长,然后把版面挤乱了,多余的如何显示成省略号?</option>
  10.         <option>或者限制住下拉框的跨度也行?</option>
  11.         <option>style="width:100px;"</option>
  12.         <option>这种已经试过了,没用!</option>
  13.     </select>
  14. </body>
  15. </html>

这么长肯定会影响到布局的,那么改怎么办呢?

这样?

  1. <option style="width:100px;">下拉框里的字太多了,下拉框会变长,然后把版面挤乱了,多余的如何显示成省略号?</option>

没用……

好吧,把下面这段代码放进去看看效果~

  1. <script type="text/javascript">
  2.         function cutOption(selectObj , length) {
  3.             this.selectObj = selectObj;
  4.             this.length = length;
  5.         }
  6.         cutOption.prototype.init = function() {
  7.             this.options = this.selectObj.getElementsByTagName('option');
  8.             for(i=0 , j=this.options.length ; i<j ; i++ )
  9.             {
  10.                 text = this.options[i].firstChild.nodeValue;
  11.                 if(text.length<=this.length)
  12.                 {
  13.                     return;
  14.                 }
  15.                 else {
  16.                     this.options[i].innerHTML = text.substring(0,this.length) + '...';
  17.                 }
  18.             }
  19.         }
  20.         obj = document.getElementById('a');
  21.         //想要几个字就改第二个参数;
  22.         var optionClass = new cutOption(obj , 5);
  23.         optionClass.init();
  24.     </script>
  25. </j></script>

不错吧?

你可能对这个有点兴趣:

我也要评论