Как реализовать text-карусель для большого текста в небольших пространствах с помощью jQuery? - PullRequest
0 голосов
/ 02 июля 2018

Я бы хотел, чтобы длинный текст отображался динамически в div с небольшой шириной. Я видел этот эффект на некоторых мобильных телефонах:

First part of large text

Next parts of large text

Когда отображается последняя часть текста, карусель влияет на изменение направления и начинается снова.

Я не могу найти ни одного плагина или примера, связанного с этим.

Как я могу реализовать это с jQuery ?

1 Ответ

0 голосов
/ 02 июля 2018

Я не уверен, существует ли такая библиотека, но я только что создал ее реализацию, используя только jQuery, основываясь на вашем вопросе.

Дайте мне знать, если у вас есть какие-либо вопросы о том, как это работает, и надеюсь, что это поможет!

// adjust these:
var loopScrollSpeed = 5;    // adjust speed (lower = slower)
var loopPauseLength = 1000; // pause in miliseconds
var loopSelector = '.loop-text';

// create our function:
function loopText(el, widthDiff, starting) {
  el.animate({
    'left': starting ? -widthDiff : 0
  }, widthDiff * 100 / loopScrollSpeed, 'linear', function() {
    setTimeout(function() {
      loopText(el, widthDiff, !starting);
    }, loopPauseLength);
  });
}

// loop through all elements with our selector
$(loopSelector).each(function() {
  el = $(this).find('span');
  widthDiff = el.width() - $(this).width();
  if (widthDiff > 0) {
    loopText(el, widthDiff, true);
  }
});
.loop-text {
  /* adjust these: */
  border: 1px solid blue;
  width: 150px;

  /* leave these: */
  overflow: hidden;
  position: relative;
  text-align: center;
}

.loop-text span {
  white-space: nowrap;
  position: relative;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class="loop-text">
  <span>The Beatles &mdash; A Day in the Life</span>
</div>

<br>

<div class="loop-text">
  <span>Text fits - no scroll</span>
</div>

<br>

<div class="loop-text">
  <span>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</span>
</div>
...