jquery 按长度限制文本

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1723650/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 12:02:28  来源:igfitidea点击:

jquery limit text by length

jquerycsstextformatting

提问by usertest

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

我可以在使用 jQuery 的多个字符后隐藏 DIV 中的文本吗?

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.

到目前为止,我认为它会像这样 - jQuery 会循环浏览文本,直到达到一定数量的字符。然后它会将一个 DIV 从该位置包装到文本的末尾,然后可以使用 hide() 方法将其隐藏。我不确定如何插入该换行文本。

Any other way around this would also be appreciated.

任何其他方式也将不胜感激。

Thanks.

谢谢。

回答by Swadesh

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.

如果超过 10 个字符,上面的 jquery 代码将隐藏 div 文本以及广告......最后解释还有更多内容。

回答by zyON

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>

回答by Bert

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()

});

回答by Tameshwar

$.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);

回答by jessegavin

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>

回答by James Black

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.

如果将 onkeydown 事件处理程序放在 body 标记上,则可以计算感兴趣的 div 中的长度,然后可以在完成后隐藏它,并删除事件处理程序。