怎样让英文自动换行且不断词

本文介绍了一种使英文文本自动换行且不断词的方法,通过在换行处给英文单词加上换行连字符,使得文本既符合印刷规范又保持了阅读的连续性。此外还提供了一种实现英文文本两端对齐的技术方案。

想让英文自动换行且不断词,就得在换行处给英文单词加上换行连字符"-",这样才能符合印刷规范。
下面举个例子:
<style>body{background-color:black;color:#CCCCFF;text-align:center}</style>
<script>
function wrap(str,len){
    return str.replace(new RegExp("(.{"+len+"})","igm"),"$1<br/>").replace(/(/w<br//>)(/w)/igm,'$1<font color=#00ff00>-<//font>$2');
}
document.write(wrap(new Array(30).join("Everything has an beginning has an end..."),50));
</script>

或采用英文字段两端对齐的方法,这样两边切齐,比较规矩:

英文对齐:<br>
<div style="font-size:12px;width:300;text-align:justify;text-justify:inter-ideograph">¨Crepower¨ Brand Belts, Chains and other Transmission Parts are manufactured under ISO9001 certified quality-control system. With improved quality material and well-organized production procedures, ¨Crepower¨ power transmission products have noticeably fatigue strength and long-service life.We can supply all types and sizes according to the related standards and customers’ requirements and</div>
<br>

.content {
position: absolute; left: 355px; top: 50px; width: 219px; height:250px;
line-height:150%;text-align:justify;text-justify:inter-ideograph;
/* 注意:设置两端对齐不能强制换行 否则不起作用 即不能加入word-break : break-all;*/

另外强制不换行的代码是white-space:nowrap;

.contenttitle {
position: absolute; left: 355px; top: 20px; width: 219px; height:30px;
line-height:150%;font-size:13px; font-weight:bold; color:#FF3201;
vertical-align:middle;white-space:nowrap; overflow:hidden;

/*强制不换行 zdz的作品,流风的作品*/
}
}

你提到的“**中英文会有差异,英文换行不对**”,是 `textarea` 自适应高度中最常见、最棘手的问题之一。 --- ## ✅ 问题本质 > **英文(尤其是长单)在 `div` 和 `textarea` 中的换行行为不一致**,导致: > > - `div` 提前断行 ✅ > - 实际 `textarea` 不断行 ❌ > - 结果:自适应高度多出一行 → “换行错误” --- ### 🔍 典型场景复现 ```text 输入内容:"supercalifragilisticexpialidocious hello world" 容器宽度:刚好能放下这个单但不断行 ``` | 元素 | 行为 | |------|------| | `textarea` | 默认允许长英文溢出或整体换行(取决于 `white-space`) | | `div` + `word-wrap: break-word` | 可能在母间断开(如 `super...`) | 👉 导致测量高度 > 实际所需高度 → **误判换行** --- ## ✅ 根本原因分析 | 原因 | 说明 | |------|------| | 📌 `textarea` 的换行策略由浏览器实现控制 | 并非所有样式都能通过 CSS 模拟 | | 📌 英文是否可断开?取决于 `hyphens`, `word-break`, `overflow-wrap` | 默认情况下 `textarea` **不会在母中间断开英文** | | 📌 `div` 使用 `word-wrap: break-word` 会在任意位置断开 | 导致提前换行 | | 📌 体微小差异或 sub-pixel 渲染 | 造成符实际占用宽度不同 | --- ## ✅ 解决方案:精准模拟 `textarea` 换行行为 我们需要让 `tempDiv` 的文本布局行为 **尽可能接近原生 `textarea`**。 ### ✅ 最佳实践配置如下: ```css tempDiv.style.cssText = ` position: absolute; top: -9999px; left: -9999px; visibility: hidden; /* 👇 关键:匹配 textarea 的默认文本行为 */ white-space: pre-wrap; /* 保留空格和换行自动换行 */ overflow-wrap: break-word; /* 只有无法断时才在母间断开(现代标准) */ word-break: normal; /* 禁止 break-all 强制断开 */ /* 👇 体完全一致 */ font-family: ${computedStyle.fontFamily}; font-size: ${computedStyle.fontSize}; font-weight: ${computedStyle.fontWeight}; font-style: ${computedStyle.fontStyle}; line-height: ${computedStyle.lineHeight}; letter-spacing: ${computedStyle.letterSpacing}; /* 👇 精确宽度:仅文本内容区 */ width: ${contentWidth}px; padding: 0; margin: 0; border: none; box-sizing: content-box; `; ``` ### ✅ 特别注意点 #### ✅ 1. `overflow-wrap: break-word` vs `word-break: break-all` - ✅ `overflow-wrap: break-word` → 长单只有放不下时才在中间断开(更接近 `textarea`) - ❌ `word-break: break-all` → 强制在任意符间断开(中文 OK,英文会提前断) > ⚠️ 所以你应该用: > ```js > tempDiv.style.overflowWrap = 'break-word'; > tempDiv.style.wordBreak = 'normal'; > ``` #### ✅ 2. 计算 `contentWidth` 必须精确 ```js const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0; const paddingRight = parseFloat(computedStyle.paddingRight) || 0; const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0; const borderRight = parseFloat(computedStyle.borderRightWidth) || 0; const contentWidth = textarea.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight; ``` > ✅ 确保 `tempDiv` 的宽度等于 `textarea` 内部文本可用宽度 #### ✅ 3. 使用 `pre-wrap` 而不是 `pre-line` 或 `normal` - `white-space: pre-wrap` → 保留空格和换行符,自动换行 ✅(与 `textarea` 一致) --- ## ✅ 完整修复后的 `resize` 函数(支持中英文正确换行) ```js const resize = () => { setTimeout(() => { const textarea = el.querySelector('.el-textarea__inner'); if (!textarea) return; textarea.style.height = 'auto'; const computedStyle = window.getComputedStyle(textarea); // 计算真实文本区域宽度 const paddingLeft = parseFloat(computedStyle.paddingLeft) || 0; const paddingRight = parseFloat(computedStyle.paddingRight) || 0; const borderLeft = parseFloat(computedStyle.borderLeftWidth) || 0; const borderRight = parseFloat(computedStyle.borderRightWidth) || 0; const contentWidth = textarea.clientWidth - paddingLeft - paddingRight - borderLeft - borderRight; // 创建临时 div const tempDiv = document.createElement('div'); tempDiv.style.cssText = ` position: absolute; top: -9999px; left: -9999px; visibility: hidden; white-space: pre-wrap; overflow-wrap: break-word; word-break: normal; font-family: ${computedStyle.fontFamily}; font-size: ${computedStyle.fontSize}; font-weight: ${computedStyle.fontWeight}; font-style: ${computedStyle.fontStyle}; line-height: ${computedStyle.lineHeight}; letter-spacing: ${computedStyle.letterSpacing}; text-transform: ${computedStyle.textTransform}; width: ${contentWidth}px; padding: 0; margin: 0; border: none; box-sizing: content-box; `; // 设置内容(空值用零宽符占位) tempDiv.textContent = textarea.value || '\u200B'; document.body.appendChild(tempDiv); // 获取测量高度 let height = tempDiv.offsetHeight; // 单行高度估算 const fontSize = parseFloat(computedStyle.fontSize); const lineHeight = computedStyle.lineHeight; const singleLineHeight = isNaN(parseFloat(lineHeight)) ? fontSize * 1.2 : parseFloat(lineHeight); if (!textarea.value) { height = singleLineHeight; } // 应用高度(向上取整避免亚像素误差) textarea.style.height = Math.ceil(height) + 'px'; document.body.removeChild(tempDiv); }, 0); }; ``` --- ## ✅ 验证测试建议 ### 测试用例 1:长英文 ```text supercalifragilisticexpialidocious ``` - 在 `textarea` 中应整体换行或滚动(不断开) - `tempDiv` 也不应在母中间断开 ### 测试用例 2:混合中英文 ```text 这是一个 longEnglishWord 测试 ``` - 中文正常换行 - 英文作为一个整体参与换行判断 ### 测试用例 3:连续空格或换行符 ```text hello\n\nworld ``` - `pre-wrap` 会保留换行符 → 正确换行 --- ## ✅ 进阶优化建议(可选) ### ✅ 添加 `font-variant` 和 `text-indent` ```js font-variant: ${computedStyle.fontVariant}; text-indent: ${computedStyle.textIndent}; ``` ### ✅ 监听 `compositionstart` / `compositionend`(中文输入法防抖) 防止在拼音输入过程中频繁计算高度: ```js let isComposing = false; textarea.addEventListener('compositionstart', () => { isComposing = true; }); textarea.addEventListener('compositionend', () => { isComposing = false; resize(); }); textarea.addEventListener('input', () => { if (!isComposing) resize(); }); ``` --- ## ✅ 总结 | 问题 | 解决方案 | |------|----------| | 英文换行提前 | 改用 `overflow-wrap: break-word` + `word-break: normal` | | 宽度不一致 | 精确计算 `contentWidth = clientWidth - padding - border` | | 中英文差异 | 使用 `pre-wrap` 保留空白和换行 | | 空内容塌陷 | 使用 `\u200B` 占位 | | 输入法跳动 | 监听 `composition` 事件 | 现在你的自适应指令应该能 **准确反映中英文混合文本的真实换行行为**,不再“提前换行”。 ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值