添加使段落折叠的链接到段落的最后一个可见行

时间:2015-03-04 01:59:03

标签: javascript jquery html css

我有这段代码使段落崩溃,但我想将链接(查看更多/更少)添加到段落的最后一行。目前它是在折叠段落后添加它。

$(document).ready(function() {
  var maxheight = 35;
  var showText = "More";
  var hideText = "Less";

  $('.text').each(function() {
    var text = $(this);
    if (text.height() > maxheight) {
      text.css({
        'overflow': 'hidden',
        'height': maxheight + 'px'
      });

      var link = $('<a href="#">' + showText + '</a>');
      var linkDiv = $('<span></span>');
      linkDiv.append(link);
      $(this).after(linkDiv);

      link.click(function(event) {
        event.preventDefault();
        if (text.height() > maxheight) {
          $(this).html(showText);
          text.css('height', maxheight + 'px');
        } else {
          $(this).html(hideText);
          text.css('height', 'auto');
        }
      });
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section class="text">
  <p>Photography has long been shaped by the desire to understand and explore the medium’s essential materials. Taking that spirit of invention and discovery as its point of departure, this exhibition features the work of seven artists—Matthew Brandt, Marco Breuer, John Chiara, Chris McCaw, Lisa Oppenheim, Alison Rossiter, and James Welling—who focus their investigations on the light sensitivity and chemical processing of photographic papers, challenging us to see the medium anew.</p>
</section>

1 个答案:

答案 0 :(得分:1)

这是我的解决方案的垃圾箱: http://jsbin.com/kovibo/2/edit?html,js,output

我重新调整了这个答案中的代码来创建一个返回段落第一行的插件: Use :first-line pseudo-element as a jQuery selector

我对事情的完成方式做了一些改变;希望我的评论会给你一个良好的开端。如果您对其中的任何内容有任何疑问,请与我们联系。