jQuery 文本截断(阅读更多样式) [英] jQuery text truncation (read more style)

查看:21
本文介绍了jQuery 文本截断(阅读更多样式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的问题与将文本修剪为 340 个字符"非常相似,但在jQuery.这听起来很直接,但当我四处搜索时,我找不到任何参考资料.

好的,我有一个 div $('#content') 我想将文本修剪为 'x' 个字符,可以说 '600' 但是我不想它自己打破这个词!就像不是问题..."而是问题...".

文本的其余部分会怎样?好吧,我将它隐藏起来,并会根据要求显示出来!但是等等,它应该首先删除..."并在它隐藏的位置之后立即显示文本.

这是 $('#content') 的示例结构:

<p>从前一个沉闷的午夜,当我虚弱和疲惫地思考时,在许多古色古香和好奇的书中被遗忘的知识.</p><p>写示例文本很无聊.</p><p>特别是当你笨到不会复制和粘贴的时候.哦!</p><p>一旦它庇护了大英帝国的流氓和无赖;现在袋鼠岛已经准备好了,等着你自己动手吧.冒险进入岛上崎岖的荒野,穿越未驯服的丛林和原始海滩,寻找海豹、企鹅和海狮的栖息地.认识热爱土地的当地人 - 考拉、巨蜥、针鼹和岛上特有的袋鼠.</p>

加载方式:

<块引用>

从前一个沉闷的午夜,而我思索着虚弱和疲倦,过了许多古色古香的被遗忘的卷知识.

编写示例文本是... [阅读更多]

点击阅读更多"后:

<块引用>

从前一个沉闷的午夜,而我思索着虚弱和疲倦,过了许多古色古香的被遗忘的卷绝杀.

编写示例文本很无聊.

特别是当你不够笨的时候复制和粘贴.哦!

一旦它庇护了流氓,大英帝国的恶棍;现在袋鼠岛准备好了等待你的一些错误自己的.冒险进入崎岖的荒野岛,穿越野性寻求丛林和原始海滩出海豹、企鹅和海狮群落.认识热爱土地的当地人- 考拉、巨蜥、针鼹和岛上特有的袋鼠.

<小时>

更新:我发现这两个插件的工作与这个最佳答案基本相同.然而,最佳答案具有这些插件所没有的一些功能,反之亦然!

解决方案

此代码假定标签始终是平衡的,并且唯一没有关闭的标签将是 <br/>(尽管如果需要,这可以很容易地补救).

#content {宽度:800px;清除:两者;剪辑:自动;溢出:隐藏;}.revealText {背景:白色;/* ie8的奇怪问题,滑动动画走得太远如果revealText没有背景颜色!*/}.hiddenText {}.阅读更多 {光标:指针;颜色:蓝色;}.省略号{颜色:黑色;}$('document').ready(function() {truncate('#content');$('.readMore').on('click', function() {var $hidden = $('.hiddenText');if($hidden.is(':hidden')) {$hidden.show();$(this).insertAfter($('#content')).children('.readMoreText').text(' [阅读较少] ').siblings().hide();} 别的 {$(this).appendTo($('.revealText')).children('.readMoreText').text(' [阅读更多] ').siblings().show();$hidden.hide();}});$('.readMore').click();函数截断(元素){$(element + 'p').css({display: 'inline'});var theText = $(element).html();//原始文本变量项目;//当前标签或文本区域被迭代var ConvertText = '<span class="revealText">';//表示完成结果的字符串无功限制= 154;//最大字符数(虽然最后一个单词完整保留)无功计数器 = 0;//跟踪我们走了多远(与限制相比)var lastTag;//持有对最后一个开始标签的引用var lastOpenTags = [];//存储所有开始标签的数组(它们在标签关闭时被删除)var nowHiding = false;//设置标志以表明我们现在处于隐藏阶段theText = theText.replace(/[s

]{2,}/g, ' ');//将多个空白字符合并为一个.(否则计数器将对它们进行计数.)theText = theText.replace(/(<[^<>]+>)/g,'|*|SPLITTER|*|$1|*|SPLITTER|*|');//找到所有标签,并在它们的任一侧添加一个分隔符.theText = theText.replace(/(|*|SPLITTER|*|)(s*)|*|SPLITTER|*|/g,'$1$2');//找到连续的拆分器,只替换一个.theText = theText.replace(/^[s	
]*|*|SPLITTER|*|||*|SPLITTER|*|[s	
]*$/g,'');//在开头和结尾去掉不必要的分隔符(如果有的话).theText = theText.split(/|*|SPLITTER|*|/);//在有拆分器的地方拆分文本.现在我们有一组标签和单词.for(var i in theText) {//迭代标签和单词数组.item = theText[i];//将当前迭代存储在一个变量中(为方便起见)lastTag = lastOpenTags[lastOpenTags.length - 1];//将最后一个开始标签存储在一个变量中(为方便起见)if( !item.match(/<[^<>]+>/) ) {//如果 'item' 不是标签,我们有文本if(lastTag && item.charAt(0) == ' ' && !lastTag[1].match(/span|SPAN/)) item = item.substr(1);//从块元素的开头删除空格(就像 IE 一样)以使结果跨浏览器匹配if(!nowHiding) {//如果我们还没有开始隐藏...计数器 += item.length;//将文本的长度添加到计数器.if(counter >= limit) {//如果我们超过了限制...var length = item.length - 1;//存储当前项的长度(减一).var position = (length) - (counter - limit);//获取文本中限制到达的位置.while(position != length) {//只要我们还没有到达文本的结尾...if( !!item.charAt(position).match(/[s	
]/) || position == length )//检查我们是否有空格,或者是否在末尾.休息;//如果是,则跳出循环.其他位置++;//否则,增加位置.}如果(位置!=长度)位置--;var closeTag = '', openTag = '';//为最后一个标签初始化打开和关闭标签.if(lastTag) {//如果有最后一个标签,closeTag = '</' + lastTag[1] + '>';//将关闭标签设置为最后一个标签是什么,openTag = '<'+ lastTag[1] + lastTag[2] + '>';//还有打开的标签.}//使用适当的标签创建从显示到隐藏的转换,并将其添加到我们的结果字符串中var transition = '<span class="readMore"><span class="ellipsis">...</span><span class="readMoreText">[阅读更多] </span></span>'+ closeTag + '</span><span class="hiddenText">'+ 打开标签;转换文本 += (位置 == 长度) ?(item).substr(0) + 过渡: (item).substr(0,position + 1) + transition + (item).substr(position + 1).replace(/^s/, '&nbsp;');现在隐藏=真;//现在我们正在隐藏.继续;//中断本次迭代.}}} else {//项目不是文本.那是一个标签.if(!item.match(/<br>|<BR>/)) {//如果是 <br/>标签,无视.if(!item.match(///)) {//如果它不是结束标记...lastOpenTags.push(item.match(/<(w+)(s*[^>]*)>/));//将其存储为我们找到的最近打开的标签.} else {//如果是结束标记.if(item.match(/</(w+)>/)[1] == lastOpenTags[lastOpenTags.length - 1][1]) {//如果结束标签与最后一个成对匹配打开标签...lastOpenTags.pop();//...删除最后一个开始标签.}if(item.match(/</[pP]>/)) {//检查是否是结束 </p>标签ConvertText += ('<span class="paragraphBreak"><br> <br> </span>');//如果是这样,添加两个换行符以形成段落}}}}转换文本 += (项目);//将项目添加到结果字符串中.}ConvertText += ('</span>');//在遍历所有标签和文本后,关闭 hiddenText 标签.$(element).html(convertedText);//用结果更新容器.}});<div id="内容"><p>从前一个沉闷的午夜,当我虚弱和疲惫地思考时,在许多古色古香和好奇的书中被遗忘的知识.</p><p>写示例文本很无聊.</p><p>特别是当你笨到不会复制和粘贴的时候.哦!</p><p>一旦它庇护了大英帝国的流氓和无赖;现在袋鼠岛已经准备好了,等着你自己动手吧.冒险进入岛上崎岖的荒野,穿越未驯服的丛林和原始海滩,寻找海豹、企鹅和海狮的栖息地.认识热爱土地的当地人 - 考拉、巨蜥、针鼹和岛上特有的袋鼠.</p>

My question is very similar to "Trim text to 340 chars" but in jQuery. It sounded very straight forward but when I searched around I couldn't find any reference for it.

Ok, I have a div $('#content') I want to trim the text to 'x' amount of characters lets say '600' BUT I don't want it to break the word it self! Like NOT 'The Ques...' BUT 'The Questions...'.

What happens to the rest of the text? Well, I hide it and will show it on request! But wait, it should first remove the '...' and show the text right after where it hid.

Here is the sample structure for $('#content'):

<div id="content">
    <p>Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.</p>
    <p>Writing example text is very boring.</p>
    <p>Specially when you are dumb enough not to copy and paste. Oh!</p>
    <p>Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo. </p>
</div>

How it should load:

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is... [Read More]

After click on 'Read More':

Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.

Writing example text is very boring.

Specially when you are dumb enough not to copy and paste. Oh!

Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo.


UPDATE: I have found these two plug-ins that do basically same job as this best answer. However the best answer has some functionalities that those plug-ins don't have and vice versa!

解决方案

This code presumes that tags will always be balanced, and that the only tag without a closer will be <br /> (though this could be easily remedied if needed).

#content {
    width: 800px;
    clear:both;
    clip:auto;
    overflow: hidden;
}
.revealText {
    background: white; /* Strange problem in ie8 where the sliding animation goes too far
                            if revealText doesn't have a background color!  */
}
.hiddenText {

}
.readMore {
    cursor: pointer;
    color: blue;
}
.ellipsis {
    color: black;
}

$('document').ready(function() {

truncate('#content');

$('.readMore').on('click', function() {
    var $hidden = $('.hiddenText');
    if($hidden.is(':hidden')) {
        $hidden.show();
        $(this).insertAfter($('#content')).children('.readMoreText').text(' [Read Less] ').siblings().hide();
    } else {
        $(this).appendTo($('.revealText')).children('.readMoreText').text(' [Read More] ').siblings().show();
        $hidden.hide();
    }
});

$('.readMore').click();

function truncate(element) {
    $(element + ' p').css({display: 'inline'});

    var theText = $(element).html();        // Original Text
    var item;                               // Current tag or text area being iterated
    var convertedText = '<span class="revealText">';    // String that will represent the finished result
    var limit = 154;                        // Max characters (though last word is retained in full)
    var counter = 0;                        // Track how far we've come (compared to limit)
    var lastTag;                            // Hold a reference to the last opening tag
    var lastOpenTags = [];                  // Stores an array of all opening tags (they get removed as tags are closed)
    var nowHiding = false;                  // Flag to set to show that we're now in the hiding phase

    theText = theText.replace(/[s

]{2,}/g, ' ');            // Consolidate multiple white-space characters down to one. (Otherwise the counter will count each of them.)
    theText = theText.replace(/(<[^<>]+>)/g,'|*|SPLITTER|*|$1|*|SPLITTER|*|');                      // Find all tags, and add a splitter to either side of them.
    theText = theText.replace(/(|*|SPLITTER|*|)(s*)|*|SPLITTER|*|/g,'$1$2');           // Find consecutive splitters, and replace with one only.
    theText = theText.replace(/^[s	
]*|*|SPLITTER|*|||*|SPLITTER|*|[s	
]*$/g,''); // Get rid of unnecessary splitter (if any) at beginning and end.
    theText = theText.split(/|*|SPLITTER|*|/);            // Split theText where there's a splitter. Now we have an array of tags and words.

    for(var i in theText) {                                     // Iterate over the array of tags and words.
        item = theText[i];                                      // Store current iteration in a variable (for convenience)
        lastTag = lastOpenTags[lastOpenTags.length - 1];        // Store last opening tag in a variable (for convenience)
        if( !item.match(/<[^<>]+>/) ) {                         // If 'item' is not a tag, we have text
            if(lastTag && item.charAt(0) == ' ' && !lastTag[1].match(/span|SPAN/)) item = item.substr(1);   // Remove space from beginning of block elements (like IE does) to make results match cross browser
            if(!nowHiding) {                                        // If we haven't started hiding yet...
                counter += item.length;                             // Add length of text to counter.
                if(counter >= limit) {                              // If we're past the limit...
                    var length = item.length - 1;                   // Store the current item's length (minus one).
                    var position = (length) - (counter - limit);    // Get the position in the text where the limit landed.
                    while(position != length) {                     // As long as we haven't reached the end of the text...
                        if( !!item.charAt(position).match(/[s	
]/) || position == length )   // Check if we have a space, or are at the end.
                            break;                                  // If so, break out of loop.
                        else position++;                            // Otherwise, increment position.
                    }
                    if(position != length) position--;
                    var closeTag = '', openTag = '';                // Initialize open and close tag for last tag.
                    if(lastTag) {                                   // If there was a last tag,
                        closeTag = '</' + lastTag[1] + '>';         // set the close tag to whatever the last tag was,
                        openTag = '<' + lastTag[1] + lastTag[2] + '>';  // and the open tag too.
                    }
                    // Create transition from revealed to hidden with the appropriate tags, and add it to our result string
                    var transition = '<span class="readMore"><span class="ellipsis">...</span><span class="readMoreText"> [Read More] </span></span>' + closeTag + '</span><span class="hiddenText">' + openTag;
                    convertedText += (position == length)   ? (item).substr(0) + transition
                                                                : (item).substr(0,position + 1) + transition + (item).substr(position + 1).replace(/^s/, '&nbsp;');
                    nowHiding = true;       // Now we're hiding.
                    continue;               // Break out of this iteration.
                }
            }
        } else {                                                // Item wasn't text. It was a tag.
            if(!item.match(/<br>|<BR>/)) {                      // If it is a <br /> tag, ignore it.
                if(!item.match(///)) {                         // If it is not a closing tag...
                    lastOpenTags.push(item.match(/<(w+)(s*[^>]*)>/));     // Store it as the most recent open tag we've found.
                } else {                                                    // If it is a closing tag.
                    if(item.match(/</(w+)>/)[1] == lastOpenTags[lastOpenTags.length - 1][1]) {    // If the closing tag is a paired match with the last opening tag...
                        lastOpenTags.pop();                                                         // ...remove the last opening tag.
                    }
                    if(item.match(/</[pP]>/)) {            // Check if it is a closing </p> tag
                        convertedText += ('<span class="paragraphBreak"><br> <br> </span>');    // If so, add two line breaks to form paragraph
                    }
                }
            }
        }   
        convertedText += (item);            // Add the item to the result string.
    }
    convertedText += ('</span>');           // After iterating over all tags and text, close the hiddenText tag.
    $(element).html(convertedText);         // Update the container with the result.
}
});


<div id="content">
    <p>Once upon a midnight dreary, while I pondered weak and weary,Over many a quaint and curious volume of forgotten lore.</p>
    <p>Writing example text is very boring.</p>
    <p>Specially when you are dumb enough not to copy and paste. Oh!</p>
    <p>Once it sheltered the rogues and rapscallions of the British Empire; now Kangaroo Island is ready and waiting for some derring-do of your own. Venture into the rugged wilds of the island, traversing untamed bushland and pristine beaches seeking out seal, penguin and sea lion colonies. Meet the land loving locals - koalas, goannas, echidnas and the island's own species of kangaroo. </p>
</div>

这篇关于jQuery 文本截断(阅读更多样式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆