Как скрыть / показать больше текста в пределах определенной длины (например, YouTube)
Я хочу, чтобы текст содержал только определенное количество символов / длину, и после этой длины я хочу разместить ссылку, чтобы раскрыть всю длину текста.
Ссылка будет (more...)
, И как только пользователь нажимает на ссылку (more..)
остальная часть текста будет скользить вниз.
Как бы я это сделал?
Вот пример.
blah blah blah blah blah (more...)
Когда пользователь нажимает (more..)
, он покажет весь текст.
ПРИМЕЧАНИЕ. Я беру данные о строке / строке таблицы, а не просто текст.
16 ответов
Секрет этого эффекта заключается в обертывании частей, которыми вы хотите управлять, с помощью HTML-тегов.
$(".more").toggle(function(){
$(this).text("less..").siblings(".complete").show();
}, function(){
$(this).text("more..").siblings(".complete").hide();
});
<span class="teaser">text goes here</span>
<span class="complete"> this is the
complete text being shown</span>
<span class="more">more...</span>
Демоверсия здесь: http://jsfiddle.net/zA23k/215/
$('#more').click(function(e) {
e.stopPropagation();
$('div').css({
'height': 'auto'
})
});
$(document).click(function() {
$('div').css({
'height': '40px'
})
})
Проверьте рабочий пример на http://jsfiddle.net/7Vv8u/4/
С анимацией http://jsfiddle.net/7Vv8u/5/
Нажмите на Read more, чтобы развернуть текст. Нажмите снаружи, чтобы свернуть его снова.
Я знаю, что этот вопрос немного старый (и его ответ уже выбран), но для тех, кто хочет другой вариант, который встречается с этим вопросом через Google (как я сделал), я нашел это динамическое сокращение текста:
Динамически сокращенный текст со ссылкой "Показать больше" с использованием jQuery
Я обнаружил, что это лучше, потому что вы можете установить ограничение по количеству символов, а не дополнительные интервалы в коде или установить конкретную высоту для контейнера.
Надеюсь, это поможет кому-то еще!
Показать больше, показать меньше (только при необходимости) Нет JQuery
Мне нужна была эта функциональность для RSS-канала на сайте нашей компании. Вот что я придумал:
// Create Variables
var allOSB = [];
var mxh = '';
window.onload = function() {
// Set Variables
allOSB = document.getElementsByClassName("only-so-big");
if (allOSB.length > 0) {
mxh = window.getComputedStyle(allOSB[0]).getPropertyValue('max-height');
mxh = parseInt(mxh.replace('px', ''));
// Add read-more button to each OSB section
for (var i = 0; i < allOSB.length; i++) {
var el = document.createElement("button");
el.innerHTML = "Read More";
el.setAttribute("type", "button");
el.setAttribute("class", "read-more hid");
insertAfter(allOSB[i], el);
}
}
// Add click function to buttons
var readMoreButtons = document.getElementsByClassName("read-more");
for (var i = 0; i < readMoreButtons.length; i++) {
readMoreButtons[i].addEventListener("click", function() {
revealThis(this);
}, false);
}
// Update buttons so only the needed ones show
updateReadMore();
}
// Update on resize
window.onresize = function() {
updateReadMore();
}
// show only the necessary read-more buttons
function updateReadMore() {
if (allOSB.length > 0) {
for (var i = 0; i < allOSB.length; i++) {
if (allOSB[i].scrollHeight > mxh) {
if (allOSB[i].hasAttribute("style")) {
updateHeight(allOSB[i]);
}
allOSB[i].nextElementSibling.className = "read-more";
} else {
allOSB[i].nextElementSibling.className = "read-more hid";
}
}
}
}
function revealThis(current) {
var el = current.previousElementSibling;
if (el.hasAttribute("style")) {
current.innerHTML = "Read More";
el.removeAttribute("style");
} else {
updateHeight(el);
current.innerHTML = "Show Less";
}
}
function updateHeight(el) {
el.style.maxHeight = el.scrollHeight + "px";
}
// thanks to karim79 for this function
// http://stackru.com/a/4793630/5667951
function insertAfter(referenceNode, newNode) {
referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
}
@import url('https://fonts.googleapis.com/css?family=Open+Sans:600');
*,
*:before,
*:after {
box-sizing: border-box;
}
html,
body {
height: 100%;
margin: 0;
padding: 0;
width: 100%;
}
body {
font-family: 'Open Sans', sans-serif;
}
h1 {
text-align: center;
}
.main-container {
margin: 30px auto;
max-width: 1000px;
padding: 20px;
}
.only-so-big p {
padding: 0;
margin: 0;
}
p {
font-size: 15px;
line-height: 20px;
}
hr {
background: #ccc;
display: block;
height: 1px;
width: 100%;
}
/*
NECESSARY SECTION
*/
.only-so-big {
background: rgba(178, 252, 255, .3);
height: 100%;
max-height: 100px;
overflow: hidden;
-webkit-transition: max-height .75s;
transition: max-height .75s;
}
.read-more {
background: none;
border: none;
color: #1199f9;
cursor: pointer;
font-size: 1em;
outline: none;
}
.read-more:hover {
text-decoration: underline;
}
.read-more:focus {
outline: none;
}
.read-more::-moz-focus-inner {
border: 0;
}
.hid {
display: none;
}
<div class="main-container">
<h1>Controlling Different Content Size</h1>
<p>We're working with an RSS feed and have had issues with some being much larger than others (content wise). I only want to show the "Read More" button if it's needed.</p>
<div class="only-so-big">
<p>This is just a short guy. No need for the read more button.</p>
</div>
<hr>
<div class="only-so-big">
<p>This one has way too much content to show. Best be saving it for those who want to read everything in here.</p>
<p>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia
voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi THE END!</p>
</div>
<hr>
<div class="only-so-big">
<p>Another small section with not a lot of content</p>
</div>
<hr>
<div class="only-so-big">
<p>Make Window smaller to show "Read More" button.<br> totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed?</p>
</div>
</div>
Для тех, кто просто хочет простое решение Bootstrap.
<style>
.collapse.in { display: inline !important; }
</style>
Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the
<span class="collapse" id="more"> 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged.</span>
<span><a href="#more" data-toggle="collapse">... <i class="fa fa-caret-down"></i></span>
Не забудьте включить в свой заголовок jquery и bootstrap.min.js.
Если вы не используете красивые иконки, измените <i class="fa fa-caret-down"></i>
на любую иконку по вашему выбору.
Если вам нужно какое-то законченное решение, вы можете использовать это:
http://jsfiddle.net/7Vv8u/2703/
JS (jQuery)
var text = $('.text-overflow'),
btn = $('.btn-overflow'),
h = text.scrollHeight;
if(h > 120) {
btn.addClass('less');
btn.css('display', 'block');
}
btn.click(function(e)
{
e.stopPropagation();
if (btn.hasClass('less')) {
btn.removeClass('less');
btn.addClass('more');
btn.text('Show less');
text.animate({'height': h});
} else {
btn.addClass('less');
btn.removeClass('more');
btn.text('Show more');
text.animate({'height': '120px'});
}
});
HTML
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
<div class="text-overflow">Lorem ipsum dolor sit amet, consectetur adipiscing 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.</div>
<a class="btn-overflow" href="#">Show more</a>
CSS
.text-overflow {
width:250px;
height:120px;
display:block;
overflow:hidden;
word-break: break-word;
word-wrap: break-word;
}
.btn-overflow {
display: none;
text-decoration: none;
}
Это еще одно решение с использованием интерактивных статей (конечно, можно изменить на что угодно).
Изменить: Если вы хотите использовать CSS-анимацию, вы должны использовать MAX-HEIGHT вместо HEIGHT
Javascript
$(".container article").click(function() {
$(this).toggleClass("expand");
})
CSS
.container {
position: relative;
width: 900px;
height: auto;
}
.container article {
position: relative;
border: 1px solid #999;
height: auto;
max-height: 105px;
overflow: hidden;
-webkit-transition: all .5s ease-in-out;
-moz-transition: all .5s ease-in-out;
transition: all .5s ease-in-out;
}
.container article:hover {
background: #dadada;
}
.container article.expand {
max-height: 900px;
}
HTML
<div class="container">
<article class="posts-by-cat_article-222">
<h3><a href="http://google.se">Section 1</a></h3>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
</article>
<article class="posts-by-cat_article-222">
<h3><a href="http://google.se">Section 2</a></h3>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
<p>This is my super long content, just check me out.</p>
</article>
</div>
Вот действительно простое решение, которое сработало для меня,
<span id="text">Extra Text</span>
<span id="more">show more...</span>
<span id="less">show less...</span>
<script>
$("#text").hide();
$("#less").hide();
$("#more").click( function() {
$("#text").show();
$("#less").show();
$("#more").hide();
});
$("#less").click( function() {
$("#text").hide();
$("#less").hide();
$("#more").show();
});
</script>
Поместите текст внутри
Your Text Here
и скопируйте скрипт в ваш файл js. Вы готовы к работе. Рабочий код для увидеть больше.. и увидеть меньше.. вариантов. Работает как с динамическими, так и со статическими текстами
<div class="item">
Your Text Here
</div>
<script type="text/javascript">
$(function(){ /* to make sure the script runs after page load */
$('.item').each(function(event){ /* select all divs with the item class */
var max_length = 150; /* set the max content length before a read more link will be added */
if($(this).html().length > max_length){ /* check for content length */
var short_content = $(this).html().substr(0,max_length); /* split the content in two parts */
var long_content = $(this).html().substr(max_length);
$(this).html(short_content+'<a href="#" class="read_more">Show More</a>'+
'<span class="more_text" style="display:none;">'+long_content+'</span>'+'<a href="#" class="read_less" style="display:none;">Show Less</a>'); /* Alter the html to allow the read more functionality */
$(this).find('a.read_more').click(function(event){ /* find the a.read_more element within the new html and bind the following code to it */
event.preventDefault(); /* prevent the a from changing the url */
$(this).hide(); /* hide the read more button */
$('.read_less').show(); /* show read less button */
$(this).parents('.item').find('.more_text').show(); /* show the .more_text span */
});
$(this).find('a.read_less').click(function(event){
event.preventDefault();
$(this).hide(); /* hide the read more button */
$('.read_less').hide();
$('.read_more').show();
$(this).parents('.item').find('.more_text').hide();
});
}
});
});
</script>
Другое возможное решение, что мы можем использовать 2 элемента HTML для хранения краткого и полного текста. Следовательно, мы можем показать / скрыть соответствующий элемент HTML:-)
<p class="content_description" id="brief_description" style="display: block;"> blah blah blah blah blah </p><p class="content_description" id="complete_description" style="display: none;"> blah blah blah blah blah with complete text </p>
/* jQuery code to toggle both paragraph. */
(function(){
$('#toggle_content').on(
'click', function(){
$("#complete_description").toggle();
$("#brief_description").toggle();
if ($("#complete_description").css("display") == "none") {
$(this).text('More...');
} else{
$(this).text('Less...');
}
}
);
})();
Обновленное решение @Hussein с высотой предварительного просмотра, которая адаптируется к количеству строк в абзаце.
Итак, с этим фрагментом кода: - Вы можете выбрать количество строк, которые вы хотите показать в предварительном просмотре, это будет работать для всех размеров экрана, даже если размер шрифта отзывчив. - Нет необходимости добавлять классы или внутреннее редактирование, чтобы отделить предварительный просмотр от всего контента.
http://jsfiddle.net/7Vv8u/5816/
var h = $('div')[0].scrollHeight;
divLineHeight = parseInt($('div').css('line-height'));
divPaddingTop = parseInt($('div').css('padding-top'));
lineToShow = 2;
divPreviewHeight = divLineHeight*lineToShow - divPaddingTop;
$('div').css('height', divPreviewHeight );
$('#more').click(function(e) {
e.stopPropagation();
$('div').animate({
'height': h
})
});
$(document).click(function() {
$('div').animate({
'height': divPreviewHeight
})
})
Так много ответов и все они хороши, но я предложу свои, может быть, кому-то это пригодится.
У нас есть HTML в шаблоне:
<div class="listing-item-excerpt" id="listing-item-excerpt-<?= $task['id'] ?>">
<?= mb_substr($txt, 0, 150) ?><span class="complete_txt"><?= mb_substr($txt, 150) ?></span>
<a href="javascript: show_more_less(<?= $task['id'] ?>);void(0);" class="more_less_btn" data-more-txt="<?= __('... show more') ?>" data-less-txt=" <?= __('show less') ?>" data-state="0"><?= __('... show more') ?></a>
</div>
Функция JS для переключения, которая:
function show_more_less(task_id) {
var btn = jQuery('#listing-item-excerpt-' + task_id).find('.more_less_btn');
var txt_container = jQuery('#listing-item-excerpt-' + task_id).find('.complete_txt');
var state = parseInt(jQuery(btn).data('state'), 10);
if (state === 0) {
jQuery(txt_container).show();
jQuery(btn).text(jQuery(btn).data('less-txt'));
jQuery(btn).data('state', 1);
} else {
jQuery(txt_container).hide();
jQuery(btn).text(jQuery(btn).data('more-txt'));
jQuery(btn).data('state', 0);
}
}
Другим хорошим решением может быть установка фиксированной высоты в вашем контейнере div, чтобы отображалась только часть вашего текста, а затем вставка функции, которая при нажатии на ссылку (что-то вроде "еще ...") меняет высоту div на auto CSS:
`$("#more").click(function(){
$ (". контейнер").css({"высота": "авто"});});`
Вы можете связать текстовое расширение с фактической текстовой ссылкой, как мне нужно было сделать, используя код с этой страницы, в итоге я получил:
<a href="#" id="emailvisible">
<H5>Change your email</H5>
</a>
<h5 id = "emailshow">To change the email enter your current email, the new email, and then click the submit button.</h5>
$.fn.clicktoggle = function(a, b) {
return this.each(function() {
var clicked = false;
$(this).click(function() {
if (clicked) {
clicked = false;
return b.apply(this, arguments);
}
clicked = true;
return a.apply(this, arguments);
});
});
};
$("#emailvisible").toggle(function(){
$(this).text("Change your email").siblings("#emailshow").show();
}, function(){
$(this).text("Change your email").siblings("").hide();
});
#emailshow{
display:none;
}
HTML
<div>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>asdasdasdasd
<br>
</div>
<a id="more" href="#">Read more </a>
<a id="less" href="#">Read less </a>
CSS
<style type="text/css">
div{
width:100px;
height:50px;
display:block;
border:1px solid red;
padding:10px;
overflow:hidden;
}
</style>
JQuery
<link rel="stylesheet"
href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/themes/start/jquery-ui.css"
type="text/css" media="all" />
<script type="text/javascript">
var h = $('div')[0].scrollHeight;
$('#more').click(function(e) {
e.stopPropagation();
$('div').animate({
'height': h
})
$('#more').hide();
$('#less').show();
});
$('#less').click(function(e) {
$('#more').show();
$('#less').hide();
});
$(document).click(function() {
$('div').animate({
'height': '50px'
})
})
$(document).ready(function(){
$('#less').hide();
})
</script>
Вы можете использовать как это
$(".jsgrid-cell").each(function(i,v){
var txt=$(v).text();
if(txt.length>100){
var shortText=txt.substring(0, 100)+
"<span onclick='$(this).hide();$(this).next().toggle();'>"+
"..."+
"</span>"+
"<span style='display:none'>"+
txt.substring(100, txt.length)+
"</span>";
$(v).html(shortText );
}
});