Как создать функцию «Показать больше» и «Показать меньше» для скрытия текста с помощью JavaScript?

Опубликовано: 1 Декабря, 2021

Функции «Показать больше» и « Показать меньше» могут быть полезны на веб-сайтах с большим объемом текста, например на сайтах новостей и журналов, содержащих много статей на одной странице. Это может помочь дизайнеру веб-страницы дать пользователю свободу читать больше или меньше текста по мере необходимости.

Количество отображаемого контента можно изменить, нажимая на кнопки. Вместо того, чтобы показывать полный абзац на веб-странице, сначала отображается только некоторая часть текста, и добавляется кнопка, которая показывает больше текста. Размер текста, который должен отображаться после и до нажатия кнопки, может быть решен разработчиком.

Вышеупомянутый подход может быть реализован с помощью простого условия if-else, которое проверяет текущий статус текста и показывает или скрывает его на этом основании. Пример ниже иллюстрирует этот метод:

HTML

<!DOCTYPE html>
< html >
< head >
< style >
/* Initially, hide the extra text that
can be revealed with the button */
#moreText {
/* Display nothing for the element */
display: none;
}
</ style >
</ head >
< body >
< h1 style = "color: green;" >
GeeksforGeeks
</ h1 >
< h3 >Show More and Show Less Example</ h3 >
< p >
GeeksforGeeks was born out of necessity-
a need to provide a convenient and
one-stop educational portal to all the
students of Computer Science.
< span id = "points" >...</ span >
<!-- Define the text that would be
hidden by default and only shown
when clicked on the button -->
< span id = "moreText" > This necessity was
as personal to me as it was universal.
This need combined with my passion for
teaching resulted in GeeksforGeeks as
we know today. My message to you, in
our inaugural edition of Geeks Digest,
would be that if you are looking for
a problem to work on, you don't need
to look very far for it. All you should
do is to look around yourself.
</ span >
</ p >
<!-- Trigger toggleText() when the
button is clicked -->
< button onclick = "toggleText()" id = "textButton" >
Show More
</ button >
< script >
function toggleText() {
// Get all the elements from the page
var points =
document.getElementById("points");
var showMoreText =
document.getElementById("moreText");
var buttonText =
document.getElementById("textButton");
// If the display property of the dots
// to be displayed is already set to
// 'none' (that is hidden) then this
// section of code triggers
if (points.style.display === "none") {
// Hide the text between the span
// elements
showMoreText.style.display = "none";
// Show the dots after the text
points.style.display = "inline";
// Change the text on button to
// 'Show More'
buttonText.innerHTML = "Show More";
}
// If the hidden portion is revealed,
// we will change it back to be hidden
else {
// Show the text between the
// span elements
showMoreText.style.display = "inline";
// Hide the dots after the text
points.style.display = "none";
// Change the text on button
// to 'Show Less'
buttonText.innerHTML = "Show Less";
}
}
</ script >
</ body >
</ html >

Выход: