jQuery文本截断(了解更多样式) [英] jQuery text truncation (read more style)
问题描述
我的问题与 将文本修剪为340个字符非常相似,但在 jQuery 。听起来很简单,但是当我四处搜寻时,找不到任何参考。
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.
好,我有一个div $(' #content')
我想将文本修整为'x'个字符,让我们说'600'
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.
以下是$('#content')的示例结构:
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>
应如何加载:
一旦午夜沉闷,而我
却想着疲软和疲倦,在许多
古朴和好奇的被遗忘的
绝杀中。
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]
点击阅读更多后:
午夜沉闷时,我
思索着软弱和疲倦,在很多
的古朴和好奇的被遗忘的
知识中。
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!
一旦它庇护了大英帝国的流氓和
响尾蛇;现在,
袋鼠岛已经准备就绪,
等待自己的
的一些小事。冒险进入岛上崎s的荒野,穿越未被驯服的
灌木丛和原始海滩,寻找
的海豹,企鹅和海狮
的殖民地。结识那些热爱土地的当地人
-考拉,果阿人,针ech和岛上自己的袋鼠。
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!
- jTruncate
- Truncate
推荐答案
此代码假定标签将始终处于平衡状态,并且没有标签的唯一标签将是< br />
(尽管
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\n\r]{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\t\r]*\|\*\|SPLITTER\|\*\||\|\*\|SPLITTER\|\*\|[\s\t\r]*$/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\t\n]/) || 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/, ' ');
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屋!