You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS文字动画拆分字符为span后,如何实现仅空格处换行?

Fixing Line Breaks to Only Occur at Spaces When Wrapping Characters in Spans

Got it, let's tackle this line break problem. The issue here is that when you wrap every non-whitespace character in an inline-block span, the browser treats each span as a separate inline-level element. That means it can break the line between any of these spans, not just at spaces—hence the random line breaks you're seeing.

To fix this, we need to ensure that entire words stay together (so line breaks only happen at spaces), while still keeping each character wrapped for the animation. Here's how to adjust your code:

Step 1: Modify the JavaScript to Wrap Words First

Instead of wrapping individual non-whitespace characters directly, we'll split the text into words and spaces, wrap each word's characters in spans, and keep spaces intact. We'll also wrap each word in a container to prevent internal line breaks.

// Wrap every letter in a span, but keep words intact
var textWrapper = document.querySelector('.rks1');
// Split text into words and spaces (preserves spaces as separate elements)
textWrapper.innerHTML = textWrapper.textContent.split(/(\s+)/).map(function(item) {
  // If it's a space, return it as-is
  if (/\s+/.test(item)) {
    return item;
  }
  // If it's a word, wrap each character in a .letter span, then wrap the whole word in .word
  return '<span class="word">' + item.replace(/./g, '<span class="letter">$&</span>') + '</span>';
}).join('');

// Keep your existing animation code unchanged
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: '.rks1', // Fixed the target class to match your heading
    opacity: 0,
    duration: 1000,
    easing: "easeOutExpo",
    delay: 500
  });

Step 2: Update CSS to Prevent Word Internal Line Breaks

Add a rule for the .word container to ensure words don't break mid-word:

.rks1 { 
  font-weight: 900; 
  font-size: 2.5em; 
  font-family: rr; 
}
.rks1 .word {
  white-space: nowrap; /* Keep the entire word on one line */
  display: inline-block; /* Align properly with spaces */
}
.rks1 .letter { 
  display: inline-block; 
  line-height: 1em; 
}

Why This Works

  • The split(/(\s+)/) preserves spaces as separate elements, so they still act as valid line break points.
  • The .word container with white-space: nowrap ensures all characters in a word stay together—no line breaks inside the word.
  • Your character animation remains fully functional because we're still targeting the .letter spans for the anime.js effects.

内容的提问来源于stack exchange,提问作者Rakesh Suthar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 20:38:14