Html display more text

Многострочный усеченный текст с кнопкой «Показать больше» на чистом CSS

Я написал скрипт на CSS для размещения многострочного усеченного текста с кнопкой «Читать далее».

Я задался вопросом, позволяет ли CSS правильно оформить усеченный текст так, чтобы разместить в нем несколько строк? А также по нажатию кнопки «Показать больше» отобразить текст полностью.

Свойство text-overflow: ellipsis не поддерживает многострочность. Но я вспомнил о свойстве line-clamp , которое позволяет обрезать многострочный текст.

Подробнее о кнопке «Показать больше»

Для создания кнопки «Показать больше» я не мог использовать тег или . Для этого требуется label и чекбокс. Вот что получилось:

 

Hey, don't cut me off like that. I want to speak my mind and don't appreciate being put into a box.

Я разместил чекбокс прямо перед абзацем, поэтому можно использовать псевдокласс :checked для активации усечения текста:

Нажмите кнопку, и в абзаце отобразится обрезанная версия текста.

Но как насчет доступности?

Хак с чекбоксом не только семантически неправильный, но и ограничивает возможности доступа к функционалу для людей с плохим зрением. При этом присваивается для чекбокса свойство display: none. Из-за этого нарушается навигация с помощью клавиатуры. Нельзя использовать скрытый чек-бокс , а использование метки не помогает. Событие нажатия клавиши пробела/ввода не перенаправляют событие в чекбокс.

Читайте также:  Generating guid in python

Чтобы решить эту проблему, я сделал чекбокс фокусируемым, хоть и все еще невидимым.

Теперь чекбокс можно выделить, но без скринридера нельзя узнать, установлен он или нет, так как невидим. Чтобы решить эту проблему, я заставил label наследовать стиль фокуса браузера по умолчанию, когда чекбокс выделен:

Ниже приведена комбинированная демо-версия. Попробуйте нажать на кнопку с помощью мышки, а затем используя клавишу пробела.

Как отображать кнопку динамически?

Но как динамически отображать кнопку, когда текст в абзаце слишком длинный, чтобы поместиться в контейнер. Это единственная функция, которую я не смог реализовать с помощью CSS. Потому что она требует применения селектора :truncated :

.read-more < display: none; >p:truncated + .read-more

Поэтому реализовать это можно только с помощью JavaScript. Например:

const ps = document.querySelectorAll('p'); const observer = new ResizeObserver(entries => < for (let entry of entries) < entry.target.classList[entry.target.scrollHeight >entry.contentRect.height ? 'add' : 'remove']('truncated'); > >); ps.forEach(p => < observer.observe(p); >);

А вот расширенная демо-версия:

Источник

How to create a «show more» button and specify how many lines of text can be initially shown

I’m looking for a way to create a slide out ‘show more’ feature on my responsive site, which cuts off after two lines of a paragraph. I’ve achieved this before with a static website, by applying a set height to the container and using overflow: hidden , and then animating the height of the container. But being responsive, the container squashes the text at different browser widths, so the text might take up more/less room. Also there may be different content above the paragraph each time pushing it down. So the setting height might not cover two lines exactly. Please check out this jsFiddle: http://jsfiddle.net/XVAzU/ if you need to demonstrate. So I need to cut off after two lines of the paragraph, no matter what width the container is or what comes before or after that paragraph. Thanks for looking!

Using CSS you can apply line-height: 1em and height: 2em which should always show two lines. I don’t know about cross-browser compatibility but the DEMO I attached to my answer shows only two lines of the text as expected in Chrome, FireFox, IE9 and IE8.

4 Answers 4

Starting from your fiddle and wrapped the content into a with a default class of content , used for selection and a class called hideContent which will be swapped with showContent when clicking the show more/show less link.

I also removed the

the text was in. The text is now within the content-div and we are also now able to apply correct height and line-height settings.

I’m assuming setting the line-height will ensure it is the same in all browsers. I’m not 100% certain on that though.

I attached a click event to the «show more» link which switches the classes on the div using jQueryUI switchClass():

$(".show-more a").on("click", function() < var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if(linkText === "SHOW MORE")< linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); >else < linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); >; $this.text(linkText); >);​ 

JsFiddle Demo — show more / show less and applying line-height and animation

$(".show-more a").on("click", function() < var $this = $(this); var $content = $this.parent().prev("div.content"); var linkText = $this.text().toUpperCase(); if (linkText === "SHOW MORE") < linkText = "Show less"; $content.switchClass("hideContent", "showContent", 400); >else < linkText = "Show more"; $content.switchClass("showContent", "hideContent", 400); >; $this.text(linkText); >);
div.text-container < margin: 0 auto; width: 75%; >.hideContent < overflow: hidden; line-height: 1em; height: 2em; >.showContent < line-height: 1em; height: auto; >.showContent < height: auto; >h1 < font-size: 24px; >p < padding: 10px 0; >.show-more

The above code is an example only but should get you started into the right direction.

I was working on something similar, but i think i like your solution more. Just as an alternative jsfiddle.net/XVAzU/4. I would set the initial class to showContent though, and replace it with the hideContent class in js on load of the document, just for people that have js disabled.

@owen: Let me know if this is what you were looking for or if you need any additional help with that.

@François Wahl, looking at your jsFiddle, it looks perfect! Thank you for the time you put into this. I haven’t had time myself to test it on the actual site yet, something urgent has come up, but I’m going to mark the answer as correct, as the jsFiddle is just what I was looking for.

If you’re searching for a css only solution check this out:

  
Show less Show more

Lorem Ipsum is simply dummy text of the printing and typesetting industry.

.show-hide-text < display: flex; flex-wrap: wrap; >.show-hide-text a < order: 2; >.show-hide-text p < position: relative; overflow: hidden; max-height: 60px; // The Height of 3 rows >.show-hide-text p < display: -webkit-box; -webkit-line-clamp: 3; // 3 Rows of text -webkit-box-orient: vertical; >.show-less < display: none; >.show-less:target < display: block; >.show-less:target ~ p < display: block; max-height: 100%; >.show-less:target + a

My suggestion to solve the problem

$("#slider_desc_toogler").on( "click", function() < $('#slider_desc_toogler >i').toggleClass('fa-arrow-circle-down') $('#slider_desc_toogler > i').toggleClass('fa-arrow-circle-up') if ($("#slider_desc_toogler > i").hasClass( "fa-arrow-circle-down" )) < $(".slider_desc").css("max-height","38px"); >else $(".slider_desc").css("max-height","500px"); >);
.slider_desc < margin: 16px; margin-top: 0px; color: #333333; font-family: Arial; font-size: 14px; line-height: 18px; text-align: justify; overflow: hidden; transition: all 0.5s ease 0s; max-height: 38px; >#slider_desc_toogler < border-top: silver 1px dotted; margin-bottom: 30px; margin-top: 20px; width: 70%; margin-left: auto; margin-right: auto; >#slider_desc_toogler i
  
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 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. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.

Источник

Html display formatted text

The text is “pre-formatted” and contains a lot of whit spaces and dashes and every line has the same length (all chars have the same width). Is there a way to display the text in html without losing the format?

give a white-space: pre for the parent div. It should preserve the whitespaces. Do you know if it will contain tags ‘<' or '>‘ or a backslash ‘/’ ?

3 Answers 3

Wrap your text inside the tag.

 
+-001 This is a Line 00:12:04 002 ---------------------------------- - 003 Everthing looks good so far ------

The HTML way is to use the pre element, which has been designed for such usage, but beware that

  • To be on the safe side in formatting, put the
    tag right at the start of the first line and the

    tag right at the end of the last line. Otherwise some browsers may behave as if there were an empty line at the start or at the end of the element.

  • You still need to escape occurrences of the characters < and & in the content (there are some cases where this is not needed, but it is simplest to ignore that.

Example (where I have added a line containing the expression 1 + 1 < 3):

+-001 This is a Line 00:12:04 002 ---------------------------------- - 003 Everthing looks good so far ------ - 004 Simple as 1 + 1 < 3 ------

+-001 This is a Line 00:12:04 002 ---------------------------------- - 003 Everthing looks good so far ------ - 004 Simple as 1 + 1 < 3 ------

Источник

Оцените статью