Как сделать кнопку подробнее в html
Перейти к содержимому

Как сделать кнопку подробнее в html

  • автор:

Кнопка "Подробнее" ("Показать больше/скрыть")

С помощью данного скрипта создается кнопка "Подробнее" ("показать больше/скрыть"), которая позволяет скрывать длинный текст на веб-странице, а при необходимости открывать его. Обычно такая кнопка используется на сайтах, где публикуется много текста (блоги, новостные сайты).

Для создания такой кнопки необходимо написать следующий код:

Пример кода на JavaScript:

<script>
function readMore() <
var dots = document.getElementById(«dots»);
var more = document.getElementById(«more»);
var btn = document.getElementById(«btn»);

if (dots.style.display === «none») <
dots.style.display=»inline»;
btn.innerHTML=»Подробнее»;
more.style.display=»none»;
> else <
dots.style.display=»none»;
btn.innerHTML=»Скрыть»;
more.style.display=»inline»;
>
>
</script>

Пример HTML-кода:

Скопируйте данный код и вставьте в нужном месте на веб-странице между тегами <body> и </body> .

Результат работы скрипта

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Asperiores nostrum corporis, beatae animi cum aut sequi nam odio consequatur ipsa dicta ad quas nemo esse, a veniam. Ne . cessitatibus placeat, in. Lorem ipsum dolor sit amet, consectetur adipisicing elit. Perspiciatis magnam, nemo totam ipsum dolor quis recusandae, dolorem deleniti officiis perferendis, qui consectetur exercitationem! Quidem eveniet, quae ipsam unde illum provident.

Также можно посмотреть работу данной кнопки (плюс дополнительная стилизация) в отдельном окне.

Create a Read More Button using HTML And CSS Only

Hello Coders!! In this article, we will use HTML and CSS to create a «Read More Read Less» button. this Read More Button In Html Without Javascript Code so let’s Create this amazing mini project.

The Read More and Read Less buttons are useful when you want to hide additional information while still giving visitors a sense of what the article or post is about.

You might want to use these buttons in multiple posts or paragraphs. However, writing separate code for each button appears to be time-consuming. It may also have an impact on the performance of your website.
In this tutorial, we will create a Read More Read Less button for multiple paragraphs using only a few lines of code.

I hope you have a clear vision for the project.

Let’s have a look at our Read More Read Less Button using HTML And CSS

Step1: Adding HTML Code

The HTML is hypertext markup language is the main structure of our webpage which will help us to display our content to the browser.

All the HTML document must start with <!doctypehtml> this helps the browser to understand the code written follows the lastest HTML format.

The HTML document itself begin With and end with .

The content that will be displayed in the brower comes under the body section

.Inside the body tag main content lies.

Let’s take a look at our HTML Code.

Exit fullscreen mode

First, we’ll use the H1 tag to add the main heading of our article.
We’ll start with an article tag, then add an input of type «checkbox» inside it, and then use the label tag to add a label to our check box.
We will now add an image to our article by using the image tag.
Using the multiple paragraph tag, we will now add multiple pieces of content to our article.

Now we have the added the basic structure of our webpage . Let’s us take a look at our HTML output.

Before the code, you just need to add the CSS link to our HTML file so that we add styling to our website:

Keep note that you must add this link under the head tag .

Step2: Adding the CSS Code

Cascading Style Sheets (CSS) is a markup language for describing the presentation of a document written in HTML or XML. CSS, like HTML and JavaScript, is a key component of the World Wide Web.

Now we will look at our CSS code.

Exit fullscreen mode

After we’ve added the CSS code, we’ll go over it step by step. To save time, you can simply copy this code and paste it into your IDE. Let us now examine our code step by step.

Step1: We’ll use the HTML tag to set the background colour to white, and we will use the universal selector to set the padding and margin to zero. The box sizing was also defined as a border box. Now, we’ll style our article’s heading with the H1 tag. For our heading, we chose «Arial» as the font family. Our heading’s font size is «2 rem,» and the colour is «dark gray.» We also added a text shadow to the article’s heading.

Exit fullscreen mode

Step2: We will now style the container of our image using the element selector (figure). Here, we’ve set the top and bottom margins to zero and the right margin to «1.3 rem.» We also included the transition in our container. Now, we use «img» to define the width as 100% of our image, and the height is set to auto.

Exit fullscreen mode

Step3: Now, we use the body to set the maximum width of the article to 480px. Our article’s actual width is set to «90%,» and the font size is set to «75%.» The font family used here is sans-serif. Our article’s position is «relative.» Now, we will style the content of our article by defining the margin bottom of «3rem» and scaling the content with the zoom property.

Now, we’ll use the float property to move the image to the left in the article figure, and the float property to move the paragraph to the right in the article section. Using the (last-type-of) selector, we also set the display to «none» and the visibility to «none.»

Exit fullscreen mode

Step5: We will now style our checkbox with the input type «checkbox.» The border is set to «0» in this case. The height and width are both defined as «1px.» Padding is set to «zero,» and overflow is set to «hidden.»

The position is now defined as «absolute,» and the text is aligned to the «centre.» Using the hover selector, we will now set the background colour to «black» and the font colour to «white.»

Exit fullscreen mode

Step6: When the user clicks on the read more button, the width of our content is set to 100% using the checked selector. Also, when we set the visibility and display to «none» with the first-type-of selector and the visibility and display to «block» with the last-type-of selector. When we check the first type of selector, the content is hidden; when we check the last type of selector, the content is visible.

Exit fullscreen mode

Now we have completed our css code and belowhere is the output after styling our webpage.

Final Output Of Read More Button using HTML And CSS Only:-
Read More Read Less Button using HTML And CSS

The project is now finished, we have completed the Read More button using CSS Only. Now look at the live preview.

Now We have Successfully created the Read More button using HTML and CSS. You can use this project directly by copying it into your IDE. We hope you understood the project, If you have any doubts feel free to comment!!

If you find out this Blog helpful, then make sure to search Codewithrandom on Google for Front End Projects with Source codes and make sure to Follow the Code with Random Instagram page.

<details> , <summary>

Нативный раскрывающийся блок с контентом без магии и JavaScript.

Время чтения: меньше 5 мин

  1. Кратко
  2. Пример
  3. Как понять
  4. Как пишется
  5. Подсказки
  6. На практике
    1. Лена Райан советует
    2. Татьяна Фокина советует

    Обновлено 26 октября 2022

    Кратко

    Скопировать ссылку «Кратко» Скопировано

    Блок с раскрывающимся контентом на чистом HTML.

    Пример

    Скопировать ссылку «Пример» Скопировано

    Самый простой раскрывающийся блок выглядит вот так:

    Как понять

    Скопировать ссылку «Как понять» Скопировано

    Иногда нужно скрывать какую-то информацию на странице в специальном блоке. Чтобы в любой момент можно было кликнуть на этот блок и развернуть информацию. И свернуть обратно таким же кликом. Такой блок ещё называют «аккордеоном».

    Как пишется

    Скопировать ссылку «Как пишется» Скопировано

    Тег <details> — это интерактивный элемент, при нажатии на который открывается блок с информацией — текстом или картинками. Нередко такие элементы можно встретить на страницах с часто задаваемыми вопросами (FAQ), где в заголовке (или легенде) написан вопрос, а ответом является содержимое «аккордеона».

    Тег <summary> — это заголовок «аккордеона», так называемая легенда. Он необязателен — без него в качестве легенды будет написан текст «Подробнее», «Details» или нечто подобное — в зависимости от выбранного языка и браузера.

    Собирается «аккордеон» очень просто: в <details> вкладываем <summary> и теги с информацией, которая будет показываться при нажатии.

    По умолчанию «аккордеон» закрыт, но если мы хотим, чтобы его содержание показывалось сразу при загрузке страницы или открывать его из JavaScript, нужно добавить к нему атрибут open .

    Подсказки

    Скопировать ссылку «Подсказки» Скопировано

    �� Можно вкладывать <details> в <details> .

    �� <details> — это интерактивный элемент, но вкладывать другие интерактивные элементы в него можно.

    �� В HTML-стандарте написано, что <summary> должен быть первым ребёнком в <details> , но на деле всё прекрасно работает, даже если <summary> находится между тегами содержательной части «аккордеона».

    �� Вёрстка не ломается, если вложить <summary> в <summary> — в таком случае будет только один элемент : : marker (треугольник перед легендой).

    �� Если в «аккордеоне» будет несколько <summary> подряд, браузер будет реагировать только на первый, а остальные даже не отобразятся, хотя будут стоять в разметке.

    �� Если указать просто <summary> без <details> , то он будет вести себя как обычный <div> — блочный элемент без интерактивности.

    На практике

    Скопировать ссылку «На практике» Скопировано

    Лена Райан советует

    Скопировать ссылку «Лена Райан советует» Скопировано

    �� Если присутствует тег <summary> , то псевдоэлемент : : marker можно стилизовать — правда, он реагирует не на все свойства, но как минимум вы сможете поменять цвет и размер шрифта. Раньше для его стилизации нужно было использовать : : — webkit — details — marker .

    Татьяна Фокина советует

    Скопировать ссылку «Татьяна Фокина советует» Скопировано

    �� Можно заменить иконку по умолчанию с помощью <img> . В этом случае оставьте значение атрибута alt пустым, так как это декоративное изображение.

    �� У <summary> есть встроенная роль button . На практике скринридеры определяют роль тега по-разному. NVDA считает его кнопкой, Narrator — раскрывающим треугольником (disclosure triangle), десктопный VoiceOver — саммари (summary), а TalkBack в Firefox и мобильный VoiceOver в Safari вообще не определяют роль <summary> .

    Можно использовать явную роль button для <summary> , но так лучше не делать:

    • Это не та ситуация, где стоит явно задавать ARIA-роль и нарушать одно из правил использования WAI-ARIA.
    • VoiceOver перестанет определять состояние <details> — развёрнут или свёрнут элемент.
    • Не решит проблему с неопределяемой ролью <details> для TalkBack в Firefox и мобильного VoiceOver в Safari.

    �� Если заменить на свою иконку с треугольником по умолчанию у <summary> , это может привести к проблемам с объявлением VoiceOver, NVDA и JAWS состояния, в котором сейчас находится элемент.

    �� В Firefox есть баг, из-за которого VoiceOver читает название иконки по умолчанию и считает его частью имени элемента — краткого названия, которое скринридеры объявляют вместе с ролью.

    �� VoiceOver в Safari и JAWS в Chrome, Edge или Firefox не считают <h1> – <h6> заголовками, если они вложены в <summary> .

    �� Может показаться, что <details> и <summary> подходят для выпадающего меню. Они ведут себя похоже, но это не самое доступное решение. Вот несколько причин:

    Как сделать — Кнопка читать дальше, читать меньше

    Узнать, как создать кнопку «Читать больше — читать меньше» с помощью JavaScript.

    Пример Text

    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel . erisque enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.

    Кнопка читать дальше читать меньше

    Шаг 1) Добавить HTML:

    Пример

    <p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Phasellus imperdiet, nulla et dictum interdum, nisi lorem egestas vitae scel<span enim ligula venenatis dolor. Maecenas nisl est, ultrices nec congue eget, auctor vitae massa. Fusce luctus vestibulum augue ut aliquet. Nunc sagittis dictum nisi, sed ullamcorper ipsum dignissim ac. In at libero sed nunc venenatis imperdiet sed ornare turpis. Donec vitae dui eget tellus gravida venenatis. Integer fringilla congue eros non fermentum. Sed dapibus pulvinar nibh tempor porta.</span></p>

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *