自定义随机词生成器输出文本无法自动换行的解决方法
解决长文本自动换行问题
你的问题核心在于超长无空格的连续字符无法被普通换行规则处理,再加上元素缺少明确的宽度约束,导致word-wrap/overflow-wrap未生效。试试以下解决方案:
关键CSS调整
给#output添加针对性样式:
#output { font-family: fantasy; /* 修正原代码里的拼写错误「fantisy」 */ word-break: break-all; /* 强制在任意字符处截断换行,适配超长无空格单词 */ /* 若想优先保留单词完整性,可替换为 overflow-wrap: break-word; */ width: 100%; /* 确保元素宽度受视口/父容器限制 */ max-width: 100%; }
属性说明
word-break: break-all:无视单词边界,直接在视口边缘截断换行,专门解决极端长字符串的换行问题。overflow-wrap: break-word:优先在单词间隙换行,仅当整个单词无法容纳时才拆分,更适合常规长文本场景。
修改后的完整代码
<html> <head> <title>random words</title> <style> #output { font-family: fantasy; word-break: break-all; width: 100%; max-width: 100%; } </style> </head> <body> <h2>random word generator</h2> <div> <button>generate</button> </div> <div id="output"></div> <script> var btn = document.querySelector("button"); var output = document.getElementById("output"); btn.addEventListener("click", getSentence); function getSentence(){ var theSentence= [ 'Pneumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosiseumonoultramicroscopicsilicovolcanoconiosis', 'A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly, A long sentence that doesn\'t wrap correctly.', ]; var sentenceNum = Math.floor(Math.random() * theSentence.length); output.textContent = theSentence[sentenceNum]; } </script> </body> </html>
内容的提问来源于stack exchange,提问作者TheMotivatedGeek
相关产品推荐
相关产品推荐

