Ниже приведена неразрушающая техника, основанная на jQuery и CSS.
Учитывая это SCSS/МЕНЬШЕ:
.collapsable {
margin-bottom: 10px; /* your <p> margin-bottom */
line-height: 20px; /* your <p> line-height */
p {
line-height: inherit;
margin-bottom: inherit;
&:last-child {
margin-bottom: 0;
}
}
&.collapsed {
position: relative;
overflow: hidden;
p {
margin: 0;
}
.expand-link-container {
position: absolute;
bottom: 0; right: 0;
display: block;
line-height: inherit;
padding: 0 2px 0 5px;
background-color: #FFF;
box-shadow: -5px 0 5px 0 white;
}
}
.expand-link-container {
display: none;
}
}
И это JQuery:
function collapseHTML(shownLines, expanderLink){
// Configuration
var shownLines = typeof(shownLines) === "undefined" ? 4 : shownLines,
expanderLink = typeof(expanderLink) === "undefined" ? "[...]" : expanderLink;
$('.collapsable').each(function(){
// If current collapsable has already been collapsed once, skip
if($(this).find('.expand-link-container').length > 0) return false;
// Compute max-height from line-height and shownLines
var lineHeight = $(this).find('p').first().css('line-height');
maxHeight = parseInt(lineHeight, 10) * shownLines;
// If the current div needs collapsing
if($(this).height() > maxHeight) {
$(this)
// Collapse it
.addClass('collapsed')
.css('max-height', maxHeight)
// Append expander link
.find('p:first-child').append(
'<div class="expand-link-container">' +
' <a href="#">' + expanderLink + '</a>' +
'</div>')
// Bind click to expander link
.find('.expand-link-container a').click(function(e){
e.preventDefault();
$(this).closest('.collapsable')
.removeClass('collapsed')
.css('max-height', '');
});
}
});
}
Вызов collapseHTML()
в любом месте JavaScript заставит все div.collapse свернуть их содержание HTML.
Пример в JSfiddle
Можно щелчок ... вместо того, чтобы «читать дальше»? – kamaci
уверен, что у вас есть вся строка, что должно быть показано, просто измените 'read more' на' ... ', но я должен сообщить вам, что для точки UX у вас должна быть заметная ссылка, говорящая о чем-то подобном «читать больше» и не скрывать его. – balexandre
Расширительный плагин кажется мне хорошо. Однако как я могу привязать его к будущему элементу? – kamaci