空格导致占位符换行异常:打字训练页面开发问题咨询
Hey there! I’ve run into similar whitespace rendering quirks when building text input tools, so let’s get this sorted for your typing trainer.
The Root Cause
Your issue likely stems from how HTML handles whitespace by default—multiple spaces get collapsed into one, and unexpected line breaks can pop up when the browser tries to wrap content that has unhandled spaces. Since you’re using a contenteditable setup for typing feedback, the browser’s default whitespace rules are conflicting with your desired text layout.
Step-by-Step Solution
Adjust CSS Whitespace Handling
Add these styles to your container elements to preserve spaces and control line breaks properly:#ph, #ed { white-space: pre-wrap; /* Preserves spaces/newlines while allowing natural wrapping */ word-wrap: break-word; /* Optional: Prevents long words from overflowing the container */ width: 100%; /* Ensure the container takes full available width */ }white-space: pre-wrapis key here—it keeps all spaces intact (so your typing matches the placeholder exactly) while letting text wrap normally when it hits the container’s edge, instead of creating random line breaks from spaces.Ensure Clean Text Injection
When setting your placeholder text (thedata-placeholdercontent), make sure you’re usingtextContentinstead ofinnerHTMLto insert it into the editable area. This avoids accidental conversion of spaces into line breaks or other unwanted elements:const placeholderText = document.getElementById('ph').dataset.placeholder; document.getElementById('ed').textContent = placeholderText;Test the Flow
With these changes, your correct/incorrect character coloring should still work as expected—this fix only adjusts how whitespace is rendered, not how individual characters are styled.
This should resolve those weird line breaks caused by spaces while keeping your core typing feedback functionality intact.
内容的提问来源于stack exchange,提问作者James Pritchard

