Перенос слов только через «Пробел» После разбиения слова на класс <span>для каждого символа - PullRequest
1 голос
/ 30 мая 2020

Моя Javascript текстовая анимация должна разбивать слово на класс <span> для каждого символа, и после этого перенос слов не работает должным образом. Поскольку слова рвутся где угодно, я хочу, чтобы они рвались только в «пробел». Как я могу сделать это из JS & CSS.

введите описание изображения здесь

Вот полный код моего JS CSS & HTML


<h1 class="rks1">A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants  </h1>

<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<style>
.rks1 {
  font-weight: 900;
  font-size: 2.5em;
  font-family: rr;
}

.rks1 .letter {
  display: inline-block;
  line-height: 1em;
}
</style>

<script>

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/\S/g, "<span class='letter'>$&</span>");

anime.timeline({loop: true})
  .add({
    targets: '.rks1 .letter',
    scale: [3.5,1],
    opacity: [0,1],
    translateZ: 0,
    easing: "easeOutExpo",
    duration: 450,
    delay: (el, i) => 50*i
  }).add({
    targets: '.ml2',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });
</script>

1 Ответ

1 голос
/ 30 мая 2020

Для каждого «слова», которое вы найдете, также оберните каждое слово в диапазон и стиль, который не будет переноситься. Например,

.word {
  white-space: nowrap;
}

См .: https://developer.mozilla.org/en-US/docs/Web/CSS/white-space


Пример:

// Wrap every letter in a span
var textWrapper = document.querySelector('.rks1');
textWrapper.innerHTML = textWrapper.textContent.replace(/(\S*)/g, function(m) {
  return `<span class="word">`
    + m.replace(/\S/g, "<span class='letter'>$&</span>")
    + `</span>`;
});

anime.timeline({loop: false})
  .add({
    targets: '.rks1 .letter',
    scale: [3.5,1],
    opacity: [0,1],
    translateZ: 0,
    easing: "easeOutExpo",
    duration: 450,
    delay: (el, i) => 50*i
  }).add({
    targets: '.ml2',
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });
.rks1 {
font-weight: 900;
font-size: 2.5em;
font-family: rr;
}

.rks1 .letter {
display: inline-block;
line-height: 1em;
}

.word {
background-color: #CFF;
white-space: nowrap;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/2.0.2/anime.min.js"></script>

<h1 class="rks1">A rose is a woody perennial flowering plant of the genus Rosa, in the family Rosaceae, or the flower it bears. There are over three hundred species and thousands of cultivars. They form a group of plants  </h1>
...