jquery用于限制要显示的单词

时间:2016-03-15 07:34:21

标签: jquery-ui

我试图限制显示120个字符。其余的应该表示为“(更多..)”。这可以点击查看整个内容。当我输入desc with space..the“(更多..)“移动到第二个......如果我不使用空间......它会移动到第一行。

<h:outputScript>interaction360();
function interaction360(){
    $(document).ready(function(){
        var maxLength = 120;
        $(".show-read-more").each(function(){
            var myStr = $(this).text();
            if($.trim(myStr).length > maxLength){
                var newStr = myStr.substring(0, maxLength);
                var removedStr = myStr.substring(maxLength, $.trim(myStr).length);
                $(this).empty().html(newStr);
                $(this).append('<span class="more-text"> (more...) </span>');
            }
        });
        $(".more-text").css("color","blue");

    });
}

enter image description here

1 个答案:

答案 0 :(得分:0)

现场演示链接:CodePen

HTML code:

 <span class="more">
  Lorem ipsum dolor sit amet, consectetur adipisicing 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.
</span>


CSS代码:

.morecontent span { display: none; }
.morelink { display: block; }


jQuery代码:

$(document).ready(function() {
// Configure/customize these variables.
var showChar = 120;  // How many characters are shown by default
var ellipsestext = "...";
var moretext = "Show more ...";
var lesstext = "Show less";


  $('.more').each(function() {
    var content = $(this).html();

    if(content.length > showChar) {

        var c = content.substr(0, showChar);
        var h = content.substr(showChar, content.length - showChar);

        var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

        $(this).html(html);
    }

});

$(".morelink").click(function(){
    if($(this).hasClass("less")) {
        $(this).removeClass("less");
        $(this).html(moretext);
    } else {
        $(this).addClass("less");
        $(this).html(lesstext);
    }
    $(this).parent().prev().toggle();
    $(this).prev().toggle();
    return false;
  });
});

希望它对你有用。