
Давайте рассмотрим разные примеры того, как можно показать/скрыть текст по нажатию на кнопку. Обычно такая функция называется спойлер или аккордеон. Это когда весь текст или половина его скрыта от просмотра, и только при нажатии на кнопку, или определённый элемент, открывается весь текст.
Разнообразие реализации такой фишки, как показать/скрыть текст может быть огромное количество. Есть разный подход к технической части: на чистой JavaScript, jQuery, чистый CSS, HTML. Для WordPress можно найти специальные плагины или сделать раскрывающийся текст без плагина.
Показать скрыть текст JS
Первые примеры будут с использованием JS/jQuery. Всё представленное ниже можно «прикрутить» к любому сайту на любой платформе. Внешний вид, то есть дизайн, легко редактируется с помощью CSS.
Первый пример Посмотреть демо
JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
jQuery(document).ready(function($) {
$('.spoiler_title').click(function() {
$(this).parents('.spoiler_wrap').find('.spoiler_content').toggleClass('open');
$(this).parents('.spoiler_wrap').find('.spoiler_arrow').toggleClass('open');
});
});
</script>
HTML
<div class="spoiler_wrap">
<div class="spoiler_title">Что такое спойлер?
<span class="spoiler_arrow"><svg viewBox="-122.9 121.1 105.9 61.9"><path d="M-63.2 180.3l43.5-43.5c1.7-1.7 2.7-4 2.7-6.5s-1-4.8-2.7-6.5c-1.7-1.7-4-2.7-6.5-2.7s-4.8 1-6.5 2.7L-69.9 161l-37.2-37.2c-1.7-1.7-4-2.7-6.5-2.7s-4.8 1-6.5 2.6c-1.9 1.8-2.8 4.2-2.8 6.6 0 2.3.9 4.6 2.6 6.5 11.4 11.5 41 41.2 43 43.3l.2.2c3.6 3.6 10.3 3.6 13.9 0z"></path></svg></span>
</div>
<div class="spoiler_content">
<p>тут текст</p>
</div>
</div>
CSS
.spoiler_wrap {
position: relative;
margin-bottom: 20px;
font-size: 22px;
background: #fff;
border-radius: 5px;
height: fit-content;
}
.spoiler_title {
cursor: pointer;
}
.spoiler_title, .spoiler_content {
padding: 30px 26px;
}
.spoiler_content {
padding-top: 0;
padding-bottom: 10px;
transition: 0.15s ease-out;
height: auto;
max-height: 0px;
overflow: hidden;
margin-top: -10px;
opacity: 0;
font-size: 14px;
color: #444;
}
.spoiler_content p {
font-size: 16px;
margin: 20px 0;
color: #333;
line-height: 1.4;
}
.spoiler_content.open {
margin-top: 0;
max-height: 100%;
opacity: 1;
}
.spoiler_title .spoiler_arrow {
display: inline-block;
margin-left: 15px;
font-size: 20px;
transition: all .1s;
vertical-align: middle;
}
.spoiler_title .spoiler_arrow svg {
fill: red;
width: 13px;
}
.spoiler_title .spoiler_arrow.open {
transform: rotate(180deg);
}
Второй пример Посмотреть демо
JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(document).ready(function() {
// 250 characters are shown by default
var showChar = 250;
var dots = ".... ";
var moreText = "Показать";
var lessText = "Скрыть";
$('.show-text').each(function() {
var content = $(this).html();
if(content.length > showChar) {
var cont = content.substr(0, showChar);
var restOfTheText = content.substr(showChar, content.length - showChar);
var html = cont + '<span class="dots">' + dots + '</span><span class="morecontent"><span>' + restOfTheText + '</span><a href="" class="morelink">' + moreText + '</a></span>';
$(this).html(html);
}
});
$(".morelink").click(function() {
if($(this).hasClass("test")) {
$(this).removeClass("test");
$(this).html(moreText);
} else {
$(this).addClass("test");
$(this).html(lessText);
}
$(this).parent().prev().toggle();
$(this).prev().toggle();
return false;
});
});
</script>
HTML
<span class="show-text"> Тут текст </span>
CSS
.morecontent span {
display: none;
}
.morelink {
font-weight: bold;
color: #4682b4;
}
Третий пример Посмотреть демо
JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$('.spoiler_title').click(function() {
$(this).find('.plus-minus-toggle').toggleClass('collapsed');
$(this).parent().toggleClass('active');
});
</script>
HTML
<div class="spoiler_wrap">
<div class="spoiler_title">
Что такое аккордеон?
<div class="plus-minus-toggle collapsed"></div>
</div>
<div class="spoiler_content">
<p>Текст</p>
</div>
</div>
CSS
.spoiler_wrap {
border-bottom: 1px solid #999999;
margin-bottom: 15px;
}
.spoiler_wrap.active .spoiler_content {
max-height: 500px !important;
padding-bottom: 25px;
transition: max-height 0.5s ease, padding-bottom 0.3s ease;
}
.spoiler_wrap.active .spoiler_title {
color: #808080;
transition: color 0.3s ease;
}
.spoiler_content {
color: #090909;
font-family: serif;
font-size: 16px;
line-height: 24px;
max-height: 0;
overflow: hidden;
transition: max-height 0.5s ease, padding-bottom 0.3s ease;
}
.spoiler_content p {
margin-bottom: 25px;
}
.plus-minus-toggle {
cursor: pointer;
height: 21px;
position: absolute;
width: 21px;
left: -40px;
top: 50%;
z-index: 2;
}
.plus-minus-toggle:before,
.plus-minus-toggle:after {
background: #000;
content: '';
height: 4px;
left: 0;
position: absolute;
top: 0;
width: 21px;
transition: transform 500ms ease;
}
.plus-minus-toggle:after {
transform-origin: center;
}
.plus-minus-toggle.collapsed:after {
transform: rotate(90deg);
}
.plus-minus-toggle.collapsed:before {
transform: rotate(180deg);
}
.spoiler_title {
color: #090909;
font-family: sans-serif;
font-size: 20px;
font-weight: 800;
text-transform: uppercase;
position: relative;
cursor: pointer;
padding: 20px 0;
transition: color 0.5s ease;
}
@media screen and (max-width: 767px) {
.spoiler_title {
font-size: 18px;
}
}
Четвертый пример Посмотреть демо
JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
$(".spoiler_title").click(function() {
var container = $(this).parents(".spoiler_wrap");
var answer = container.find(".spoiler_content");
var trigger = container.find(".arrow-t");
answer.slideToggle(200);
if (trigger.hasClass("arrow-b")) {
trigger.removeClass("arrow-b");
} else {
trigger.addClass("arrow-b");
}
if (container.hasClass("expanded")) {
container.removeClass("expanded");
} else {
container.addClass("expanded");
}
});
</script>
HTML
<div class="spoiler_wrap">
<div class="spoiler_title_wrap">
<div class="spoiler_title">
Что такое спойлер?
<span class="arrow-t"></span>
</div>
</div>
<div class="spoiler_content">
<p>текст</p>
</div>
</div>
CSS
.spoiler_wrap {
margin-bottom: 40px;
}
.spoiler_title_wrap {
display: block;
padding: 0px;
}
.spoiler_title {
margin-bottom: 20px;
font-size: 22px;
font-weight: 600;
color: #000;
cursor: pointer;
display: table;
transition: all .3s ease-in-out;
position: relative;
}
.spoiler_title:hover,
.expanded .spoiler_title {
opacity: 0.7;
}
.spoiler_content {
font-size: 16px;
border-radius: 5px;
line-height: 26px;
display: none;
margin-bottom: 30px;
padding: 30px;
background: #333;
position: relative;
}
.spoiler_content p {
color: #999;
margin-bottom: 25px;
}
.spoiler_content p:last-child {
margin-bottom: 0px;
}
.arrow-t {
transform: rotate(-45deg);
display: block;
position: absolute;
top: 7px;
right: -33px;
width: 10px;
height: 10px;
background: transparent;
border-left: 3px solid #000;
border-bottom: 3px solid #000;
transition: all .3s ease-in-out;
}
.arrow-b {
transform: rotate(-224deg);
}
Пятый пример Посмотреть демо
JS
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script>
(function($) {
$.fn.iComputerSlide = function(options) {
options = $.extend({
height: 200,
btnClose: "Close",
btnOpen: "Open"
}, options);
makeWrap = function($element, options) {
return '<div class="io_item">' +
'<div class="io_item_wrap" style="max-height:' + options.height + 'px">' + $element[0].outerHTML +
'<div class="io_trans"></div>' +
'</div>' +
'<div class="io_button_wrap">' +
'<a class="io_button btn_close">' + options.btnClose + '</a>' +
'<a class="io_button btn_open">' + options.btnOpen + '</a>' +
'</div>' +
'</div>';
};
$(document).on("click", ".io_button", function() {
$(this).parents(".io_item").toggleClass("open");
});
return this.each(function() {
var $element = $(this);
$element.replaceWith(makeWrap($element, options));
});
};
})(jQuery);
$(function() {
$(".item_text").iComputerSlide({
height: 150,
btnClose: "Свернуть",
btnOpen: "Читать"
});
});
</script>
HTML
<div class="text_hide_wrap">
<div class="item_text">
<p>текст</p>
</div>
</div>
CSS
.text_hide_wrap {
max-width: 700px;
}
.item_text {
width: 100%;
padding: 20px;
}
.item_text p {
margin-bottom: 20px;
}
.io_item {
width: 100%;
padding-bottom: 20px;
}
.io_button_wrap {
text-align: center;
margin-top: 10px;
}
.io_button {
display: inline-block;
border: 1px solid #f00;
width: auto;
padding: 0 20px;
line-height: 32px;
vertical-align: top;
text-transform: uppercase;
color: #f00 !important;
font-size: 10pt;
border-radius: 22px;
cursor: pointer;
}
a.io_button:hover {
text-decoration: none;
}
.io_item .btn_close {
display: none;
}
.io_item .btn_open {
display: inline-block;
}
.io_item.open .btn_close {
display: inline-block;
}
.io_item.open .btn_open {
display: none;
}
.io_trans {
width: inherit;
position: absolute;
height: 80px;
bottom: 0;
pointer-events: none;
background: linear-gradient(to bottom, rgba(255, 255, 255, 0) 0%, rgba(255, 255, 255, 1) 100%);
transition: 1s;
}
.io_item.open .io_trans {
height: 0;
transition: 1s;
}
.io_item_wrap {
position: relative;
overflow: hidden;
max-height: 100px;
width: inherit;
transition: max-height 0.5;
}
.io_item.open .io_item_wrap {
max-height: 999px !important;
transition: max-height 1s;
}
Показать скрыть текст CSS
Подобное скрытие текста можно реализовать одними средствами CSS и HTML. И это не значит какой-то недостаток. В том плане, что будет хуже, чем с помощью JS/jQuery. Да и в целом многое зависит от поставленной задачи. И помните, всегда можно отредактировать стили под свой дизайн сайта.
Первый пример Посмотреть демо
HTML
<div class="spoiler_wrap">
<input type="checkbox" class="read-more-state" id="visible" />
<div class="spoiler_content">
<p>текст</p>
<p class="text_hide">скрытый текст</p>
<p class="text_hide">скрытый текст</p>
</div>
<label for="visible" class="read-more-trigger"></label>
</div>
CSS
.spoiler_content {
opacity: 1;
transition: opacity 0.4s ease-in-out;
}
.spoiler_content p {
text-align: left;
margin-bottom: 5px;
}
.read-more-state {
display: none;
}
.text_hide {
opacity: 0;
max-height: 0;
font-size: 0;
transition: opacity 0.4s ease-in-out;
}
.read-more-state:checked~.spoiler_content .text_hide {
opacity: 1;
font-size: inherit;
max-height: 999em;
}
.read-more-state:checked~.spoiler_content p {
margin-bottom: 20px;
}
.read-more-state~.read-more-trigger:before {
content: 'Показать всё';
}
.read-more-state:checked~.read-more-trigger:before {
content: 'Скрыть текст';
}
.read-more-trigger {
cursor: pointer;
display: inline-block;
padding: 10px 15px;
color: #fff;
font-size: .9em;
line-height: 2;
border: none;
border-radius: .25em;
margin-bottom: 15px;
background: #666;
}
Второй пример Посмотреть демо
HTML
<div class="spoiler_wrap">
<input type="checkbox" class="toggle">
<div class="spoiler_title">Что такое спойлер?</div>
<div class="icon"></div>
<div class="border"></div>
<div class="spoiler_content">
<p>текст</p>
</div>
</div>
CSS
.spoiler_wrap {
position: relative;
min-height: 30px;
margin-bottom: 15px;
}
.spoiler_title {
width: 100%;
position: absolute;
top: 0;
left: 0;
margin: 0;
height: 30px;
z-index: 1;
font-weight: 600;
font-size: 18px;
}
.toggle:checked~.spoiler_title,
.spoiler_title:hover {
color: #EA2816;
}
.icon {
height: 18px;
position: absolute;
width: 18px;
right: 0;
top: 11px;
z-index: 2;
}
.icon:before,
.icon:after {
background: #333;
content: '';
height: 4px;
right: 0;
position: absolute;
top: 0;
width: 18px;
transition: transform 500ms ease;
}
.toggle:checked~.icon:before,
.toggle:checked~.icon:after {
background: #EA2816;
}
.toggle:not(:checked)~.icon:before {
transform: rotate(180deg);
}
.toggle:not(:checked)~.icon:after {
transform: rotate(90deg);
}
.toggle {
width: 100%;
height: 40px;
margin: 0;
opacity: 0;
cursor: pointer;
position: absolute;
top: 0;
z-index: 3;
}
.border {
height: 40px;
border-bottom: 1px solid #333;
}
.toggle:checked~.border {
border-bottom: 1px solid #EA2816;
}
.spoiler_content {
padding: 15px 0 0 0;
height: 0;
overflow: hidden;
z-index: -1;
position: relative;
opacity: 0;
transition: .4s ease;
}
.toggle:checked~.spoiler_content {
height: auto;
opacity: 1;
z-index: 2;
}
.spoiler_content>p {
margin-bottom: 20px;
}
HTML-тег details: показать скрыть текст
Есть совсем простое решение, чтобы создать кнопку, при нажатии на которую открывается текст. Для этого существуют специальные теги в HTML 5, такие как <details>, <summary>. По сути, их можно использовать даже без стилей CSS. Но чтоб всё сделать красиво, конечно, желательно применить каскадную таблицу.
Пример Посмотреть демо
HTML
<details>
<summary>Что такое спойлер?</summary>
<p>текст</p>
</details>
<details open>
<summary>Открытый спойлер</summary>
<p>текст</p>
</details>
CSS
details {
min-height: 5px;
padding: 25px 70px 25px 25px;
margin: 0 auto;
position: relative;
font-size: 22px;
border: 1px solid #333;
border-radius: 10px;
box-sizing: border-box;
transition: all .3s;
}
details+details {
margin-top: 20px;
}
details[open] {
min-height: 50px;
}
details[open] summary ~ * {
animation: anspl .3s cubic-bezier(.52,.41,.75,.74);
}
@keyframes anspl {
0% {opacity: 0; transform: translateY(-50px)}
100% {opacity: 1; transform: translateY(0)}
}
details p {
color: #444;
font-weight: 400;
margin: 15px 0;
}
details p:last-child {
margin-bottom: 0px;
}
summary {
display: flex;
align-items: center;
font-weight: 500;
cursor: pointer;
}
summary:focus {
outline: none;
}
summary::-webkit-details-marker {
display: none
}
summary::before {
content: '+';
padding-right: 0.5em;
}
details[open]>summary::before {
content: '-';
}
Здравствуйте. На сайте применила Ваши эффекты (пятый пример) . На компе и телефоне на андроид — выглядит прекрасно, а на айфоне текст наезжает, в много слоев получился.
Как быть , помогите, пожалуйста? Есть может медиа-запрос или еще что, что лечит такое или просто отказаться от это метода ...Я начинающию веб-разработчик.
День добрый. Проверил на Вашем сайте через iPad и проблемы не обнаружил. Попробуйте почистить кеш в браузере. Я через safari проверял. Или попробуйте другой браузер. Если проблема останется, сделайте скриншот, чтобы я смог ее увидеть.
Андрей! Гениально! Воспользовался Вашим примером на чистом HTML/CSS! Все действительно выглядит круто! Благодарю за идею и пример!
Не за что! Рад, что кому-то пригодилось)