jquery limit text by length

2020-02-10 04:54发布

Can i hide text in a DIV after a number of characters with jQuery?

So far I think it would go something like this - jQuery would cycle through the text until it gets to a certain number of characters. It would then wrap a DIV from that position to the end of the text which could then be hidden with the hide() method. I'm not sure how to insert that wrapping text.

Any other way around this would also be appreciated.

Thanks.

6条回答
手持菜刀,她持情操
2楼-- · 2020-02-10 05:13
$.fn.textlimit = function(limit)
{
    return this.each(function(index,val)                       
    {
        var $elem = $(this);
        var $limit = limit;
        var $strLngth = $(val).text().length;  // Getting the text
        if($strLngth > $limit)
        {
          $($elem).text($($elem).text().substr( 0, $limit )+ "...");
        }
    })
};

**how to use**

$("#DivId").textlimit(60);
查看更多
甜甜的少女心
3楼-- · 2020-02-10 05:14

This will hide a part of the text

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
    "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

    <title>untitled</title>
    <style type="text/css" media="screen">
        .hide{
            display: none;
        }
    </style>
    <script src="js/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>
    <script type="text/javascript" charset="utf-8">
        $(function(){
            var $elem = $('p');         // The element or elements with the text to hide
            var $limit = 10;        // The number of characters to show
            var $str = $elem.html();    // Getting the text
            var $strtemp = $str.substr(0,$limit);   // Get the visible part of the string
            $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span>';  // Recompose the string with the span tag wrapped around the hidden part of it
            $elem.html($str);       // Write the string to the DOM 
        })
    </script>

</head>
<body>
<p>Some lenghty string goes here</p>
</body>
</html>
查看更多
Explosion°爆炸
4楼-- · 2020-02-10 05:26

I am replacing my original answer with this one.....

<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>
<script type="text/javascript">
    $(function() {
        var limit = 20;
        var chars = $("#myDiv").text(); 
        if (chars.length > limit) {
            var visiblePart = $("<span> "+ chars.substr(0, limit-1) +"</span>");
            var dots = $("<span class='dots'>... </span>");
            var hiddenPart = $("<span class='more'>"+ chars.substr(limit-1) +"</span>");
            var readMore = $("<span class='read-more'>Read More</span>");
            readMore.click(function() {
                $(this).prev().remove(); // remove dots
                $(this).next().show();
                $(this).remove(); // remove 'read more'
            });

            $("#myDiv").empty()
                .append(visiblePart)
                .append(dots)
                .append(readMore)
                .append(hiddenPart);
        }
    });
</script>
<style type="text/css">
    span.read-more { cursor: pointer; color: red; }
    span.more { display: none;  }
</style>
</head>
<body>
    <div id="myDiv">Here are all<br/> my characters.<br/> I would like to limit them to 20.</div>
</body>
</html>
查看更多
何必那么认真
5楼-- · 2020-02-10 05:29

I think the purpose can be solved much more easier way than explained above

$(function(){
  $(".title").each(function(i){
    len=$(this).text().length;
    if(len>10)
    {
      $(this).text($(this).text().substr(0,10)+'...');
    }
  });       
});

The above jquery code will hide div text if it exceeds 10 characters as well as ads ... at the end to explain that there is something more.

查看更多
Deceive 欺骗
6楼-- · 2020-02-10 05:33

Jeff I was having the same issue wanted to add the text limiter to a dynamic content so here is my solution:

// TEXT CHARACTER LIMITER 

$(document).ready(function() {

  $.fn.textlimit = function()
  { 

    return this.each(function()                       
    {

    var $elem = $(this);            // Adding this allows u to apply this anywhere
    var $limit = 22;                // The number of characters to show
    var $str = $elem.html();        // Getting the text
    var $strtemp = $str.substr(0,$limit);   // Get the visible part of the string
    $str = $strtemp + '<span class="hide">' + $str.substr($limit,$str.length) + '</span> ...';  
    $elem.html($str);
    })

  };

});

// Call the text limiter above 

$(document).ready(function() {

    $('.someGenericClass .anotherClass').textlimit()

});
查看更多
Summer. ? 凉城
7楼-- · 2020-02-10 05:34

If you put a onkeydown event handler on the body tag you can then count the length in the div of interest, and then you can hide it when done, and remove your event handler.

查看更多
登录 后发表回答