Как переключить усеченный текст в JavaScript? - PullRequest
0 голосов
/ 20 ноября 2018

Пример здесь: enter image description here

Как переключить текст с «усечь» на «полный текст»?

как и я хочу переключать полный текст, когда человек нажимает кнопку «читать дальше», а также скрывать текст, когда нажимается кнопка «скрыть текст»

Отрывок:

var textHolder = document.querySelector('.demo');
var btn = document.querySelector('.btn');


function Truancate(textHolder, limit) {
  let txt = textHolder.innerHTML;
  if (txt.length > limit) {
    let newText = txt.substr(0, limit) + ' ...';
    textHolder.innerHTML = newText;
  }
}

Truancate(textHolder, textHolder.offsetWidth / 10);



function toggleText() {
  // here i want to show full text...
  // and also -> btn.innerHTML = 'Hide Text' | 'Show Text;
}


btn.addEventListener('click', toggleText);
<section class="demo" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>

<button class="readMore btn">Read More</button>

Ответы [ 3 ]

0 голосов
/ 20 ноября 2018

Сначала необходимо сохранить полный текст в переменной, никогда не изменять эту переменную, затем сохранить усеченный текст в другой переменной и, наконец, переключаться между ними в значение переменной, чтобы установить текст для целевого элемента.

Вот синпета:

var textHolder = document.querySelector('.demo');
var fullText = textHolder.innerHTML;
var btn = document.querySelector('.btn');
var textStatus = 'full'; // use this to check the status of text and toggle;

function Truancate(textHolder, limit) {
  let txt = textHolder.innerHTML;
  if (txt.length > limit) {
    let newText = txt.substr(0, limit) + ' ...';
    textHolder.innerHTML = newText;
    textStatus = 'truncated';
  }
}

Truancate(textHolder, textHolder.offsetWidth / 10);

function toggleText() {
  // here i want to show full text...
  // and also -> btn.innerHTML = 'Hide Text' | 'Show Text;
  if (textStatus === 'truncated') {
    textHolder.innerHTML = fullText;
    textStatus = 'full';
  } else {
    Truancate(textHolder, textHolder.offsetWidth / 10);
  }
}


btn.addEventListener('click', toggleText);
<section class="demo" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>

<button class="readMore btn">Read More</button>
0 голосов
/ 20 ноября 2018

Вот еще один объектно-ориентированный способ, который можно использовать где угодно в подобной ситуации

Что вам нужно сделать, это только выполнить следующий шаг

  1. Создать контейнер-обертку с идентификатором let 'say readMoreContainer

  2. Добавить класс с именем readMoreText в раздел, содержащий текст для переключения усечения

  3. Добавить класс с именем readMoreButton к элементу кнопки.

Вы можете удалить ненужные классы и идентификаторы

var ReadMore = (function() {
  function ReadMore(limit, readMoreContainerElementSelector) {
    this.limit = limit;
    this.readMoreContainerElementSelector = readMoreContainerElementSelector;
    this.isFullTextShown = false;
    this.initializeReadMore();
  }
  ReadMore.prototype.initializeReadMore = function() {
    this.fullText = document.querySelector(this.readMoreContainerElementSelector + " .readMoreText").innerHTML;
    this.truncatedText = this.fullText.substr(0, this.limit) + ' ...';
    var that = this;
    document.querySelector(this.readMoreContainerElementSelector + " .readMoreButton").addEventListener("click", function() {
      that.performToogle();
    });
    this.performToogle();
  };
  ReadMore.prototype.performToogle = function() {
    var textToDisplay = "";
    var buttonText = "";
    this.isFullTextShown ? (textToDisplay = this.fullText, buttonText = "Read Less" ): (textToDisplay = this.truncatedText, buttonText = "Read More");
    this.isFullTextShown = !this.isFullTextShown;
    document.querySelector(this.readMoreContainerElementSelector + " .readMoreText").innerHTML = textToDisplay;
    document.querySelector(this.readMoreContainerElementSelector + " .readMoreButton").innerHTML = buttonText;
  };
  return ReadMore;
}());

var readmore = new ReadMore(100, "#readMoreContainer1");
var readmore = new ReadMore(50, "#readMoreContainer2");
<div id="readMoreContainer1">
<section class="demo readMoreText" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
<button class="readMore btn readMoreButton">Read More</button>
</div>
<hr/>
<div id="readMoreContainer2">
<section class="demo readMoreText" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course! Let's truncate a long
  line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>
<button class="readMore btn readMoreButton">Read More</button>
</div>
0 голосов
/ 20 ноября 2018

Вам не нужен JavaScript для этого. простой CSS text-overflow: ellipsis; может добиться цели.

Это лучший / стандартный способ обрезания длинного текста, потому что он усекает отображение текста в точном положении, которое зависит от размера шрифта, ширины родительского контейнера и т. Д., Что невозможно просто с помощью js , вот демо:

var textHolder = document.querySelector('.demo');
var btn = document.querySelector('.btn');

function toggleText() {
  textHolder.classList.toggle("truncate");
}

btn.addEventListener('click', toggleText);
toggleText(); //to truncate at first time
.truncate {
  text-overflow: ellipsis;
  /*BOTH of the following are required for text-overflow (overflow: hidden; and white-space: nowrap;)*/
  overflow: hidden;
  white-space: nowrap;
}
<section class="demo" id="demo">
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
  Let's truncate a long line of text so that the words don't wrap when they're not supposed to. Multi-line of course!
</section>

<button class="readMore btn">Read More</button>

Обратите внимание, что вырезание innerHTML может быть опасным, поскольку вы можете вырезать в неправильном положении и повредить открывающие / закрывающие теги HTML-кода ...

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...