chat-message div文本无法自动换行的技术问题求助
It looks like your chat messages aren’t wrapping as expected due to a combination of your custom <preBot> tag styling and some minor container constraints. Let’s fix this step by step:
1. Fix the custom <preBot> tag styling
Since <preBot> isn’t a standard HTML element, if you’ve styled it with white-space: pre (to preserve formatting), that’s preventing text from wrapping. Update its CSS to allow line breaks while keeping your desired formatting:
preBot { /* Keep your existing styles for color, alignment, etc. */ color: #your-preferred-color; text-align: left; /* Add this to enable wrapping */ white-space: pre-wrap; /* Preserves whitespace but wraps long lines */ /* OR use white-space: normal; if you don’t need to preserve extra whitespace */ }
2. Adjust the .chat-message container
Your current fixed width: 400px might not adapt well to different screen sizes. Instead, use relative sizing and improve wrapping behavior:
.chat-message { word-break: break-word; /* Breaks long words only when necessary (more user-friendly than break-all) */ max-width: 100%; /* Ensures messages don’t overflow their parent container */ white-space: normal; /* Forces standard text wrapping */ }
3. Ensure the parent container is properly constrained
Make sure the #messages (card-block) div takes the full width of its Bootstrap column:
#messages { width: 100%; }
4. Clean up redundant JavaScript
Your code currently appends the message twice (once with appendChild, once with insertBefore). Remove the redundant line since it doesn’t serve any purpose:
var message = document.createElement('div'); message.setAttribute('class', 'chat-message'); message.innerHTML = "<preBot>" + data[x].name + ": " + data[x].message + '</preBot>'; messages.appendChild(message); // Remove this line: messages.insertBefore(message, messages.nextSibling);
These changes should make your chat messages wrap naturally instead of extending off the screen.
内容的提问来源于stack exchange,提问作者DanielJomaa

