JS文字动画拆分字符为span后,如何实现仅空格处换行?
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
.wordcontainer withwhite-space: nowrapensures 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
.letterspans for the anime.js effects.
内容的提问来源于stack exchange,提问作者Rakesh Suthar

