欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

jQuery实现文字超过1行、2行或规定的行数时自动加省略号的方法

程序员文章站 2023-11-10 15:13:10
本文实例讲述了jquery实现文字超过1行、2行或规定的行数时自动加省略号的方法。分享给大家供大家参考,具体如下: ...

本文实例讲述了jquery实现文字超过1行、2行或规定的行数时自动加省略号的方法。分享给大家供大家参考,具体如下:

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title>www.jb51.net jquery自动添加省略号</title>
  <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
  <script type="text/javascript">
    $(function () {
      $(".figcaption").each(function (i) {
        var divh = $(this).height();
        var $p = $("p", $(this)).eq(0);
        while ($p.outerheight() > divh) {
          $p.text($p.text().replace(/(\s)*([a-za-z0-9]+|\w)(\.\.\.)?$/, "..."));
        };
      });
    });
  </script>
  <style>
    *{
      padding: 0px;
      margin: 0px;
    }
    .figcaption{
      width: 300px;
      height: 50px;
      /*根据父元素的高度来添加省略号
      *可以任意设置显示的行数
      */
      border: 1px solid red;
    }
  </style>
</head>
<body>
  <div class="figcaption">
    <p>
      you probably can't do it (currently?) without a fixed-width font like courier. with
      a fixed-width font every letter occupies the same horizontal space, so you could
      probably count the letters and multiply the result with the current font size in
      ems or exs. then you would just have to test how many letters fit on one line, and
      then break it up.</p>
  </div>
</body>
<script>
</script>
</html>

运行效果:

jQuery实现文字超过1行、2行或规定的行数时自动加省略号的方法

更多关于jquery相关内容可查看本站专题:《jquery字符串操作技巧总结》、《jquery操作xml技巧总结》、《jquery扩展技巧总结》、《jquery选择器用法总结》及《jquery常用插件及用法总结

希望本文所述对大家jquery程序设计有所帮助。