How to hide/show more text within a certain length (like youtube)

前端 未结 14 644
说谎
说谎 2020-11-28 21:24

I want to have a text to only be a certain amount of characters/length and after that length, I want to put a link to reveal the full length of the text.

The link w

相关标签:
14条回答
  • 2020-11-28 22:23

    The secret about this effect, is wrapping the parts that you want to control with HTML tags.

    $(".more").toggle(function(){
        $(this).text("less..").siblings(".complete").show();    
    }, function(){
        $(this).text("more..").siblings(".complete").hide();    
    });
    

    <span class="teaser">text goes here</span>
    
    <span class="complete"> this is the 
    complete text being shown</span>
    
    <span class="more">more...</span>
    

    Online demo here: http://jsfiddle.net/zA23k/215/

    0 讨论(0)
  • 2020-11-28 22:24

    If you need some complete solution, you can use this :

    http://jsfiddle.net/7Vv8u/2703/

    JS (jQuery)

    var text = $('.text-overflow'),
         btn = $('.btn-overflow'),
           h = text.scrollHeight; 
    
    if(h > 120) {
        btn.addClass('less');
        btn.css('display', 'block');
    }
    
    btn.click(function(e) 
    {
      e.stopPropagation();
    
      if (btn.hasClass('less')) {
          btn.removeClass('less');
          btn.addClass('more');
          btn.text('Show less');
    
          text.animate({'height': h});
      } else {
          btn.addClass('less');
          btn.removeClass('more');
          btn.text('Show more');
          text.animate({'height': '120px'});
      }  
    });
    

    HTML

    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</div>
    <a class="btn-overflow" href="#">Show more</a> 
    

    CSS

    .text-overflow {
      width:250px;
      height:120px;
      display:block; 
      overflow:hidden;
      word-break: break-word;
      word-wrap: break-word;
    }
    
    .btn-overflow {
      display: none;
      text-decoration: none; 
    }
    
    0 讨论(0)
提交回复
热议问题