Помните, разверните / сверните - PullRequest
0 голосов
/ 24 октября 2019

Я не могу заставить это работать. Я хочу, чтобы по умолчанию показывалось 50 символов, а остальные - когда я нажимал на «читать дальше», и наоборот, с «меньше». Еще одна проблема, которую я заметил, - когда я нажимаю кнопку «Назад» в браузере, отображается ссылка «больше / меньше», но когда я нажимаю на нее, ничего не происходит. Любые идеи о том, как я могу исправить эти две проблемы?

    $(document).ready(function() {
        // Configure/customize these variables.
        var showChar = 50;  // How many characters are shown by default
        var ellipsestext = "...";
        var moretext = "Read more";
        var lesstext = "Read less";


        $('.textControl').each(function() {
            var content = $(this).html();

            if(content.length > showChar) {

                var c = content.substr(0, showChar);
                var h = content.substr(showChar, content.length - showChar);

                var html = c + '<span class="moreellipses">' + ellipsestext+ '&nbsp;</span><span class="morecontent"><span>' + h + '</span>&nbsp;&nbsp;<a href="" class="morelink">' + moretext + '</a></span>';

                $(this).html(html);
            }
        });

        $(".morelink").click(function(){
            if($(this).hasClass("less")) {
                $(this).removeClass("less");
                $(this).html(moretext);
            } else {
                $(this).addClass("less");
                $(this).html(lesstext);
            }
            $(this).parent().prev().toggle();
            $(this).prev().toggle();
            return false;
        });
    });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<p class='textControl'>
Lorem Ipsum is simply dummied 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
</p>

1 Ответ

0 голосов
/ 24 октября 2019

Только по основам:

var extraText = ". 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";
var originalText;
$('.moreless').click(function() {
  if (this.innerHTML === 'More...') {
    this.innerHTML = 'Less...'
    originalText = $('.textControl')[0].innerHTML;
    $('.textControl')[0].innerHTML += extraText;
  } else {
    this.innerHTML = 'More...'
    $('.textControl')[0].innerHTML = originalText;
  }
});
<p class='textControl'>
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
</p>
<button class='moreless'>More...</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Сохраняет текущий текст, когда вы нажимаете «Еще ...» и , затем добавляет дополнительный текст. Это также изменяет текст кнопки на «Меньше ...». Когда текст кнопки говорит «Меньше ...», он возвращается к исходному тексту, который был сохранен как переменная.

Это просто основная идея. Чтобы он показывал по умолчанию только 50 символов, вы делаете это:

var maxText = 50;
var originalText = $('.textControl')[0].innerHTML;
var reducedText = $('.textControl')[0].innerHTML.substring(0, maxText - 1);
$('.textControl')[0].innerHTML = reducedText;
$('.moreless').click(function() {
  if (this.innerHTML === 'More...') {
    this.innerHTML = 'Less...'
    $('.textControl')[0].innerHTML = originalText;
  } else {
    this.innerHTML = 'More...'
    $('.textControl')[0].innerHTML = reducedText;
  }
});
<p class='textControl'>
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
</p>
<button class='moreless'>More...</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

Код сохраняет 50 символов при запуске, но также сохраняет исходный текст. То же самое происходит при изменении текста кнопки и текста абзаца.

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