文本手动分行 2024-01-18 前端 暂无评论 926 次阅读 ```javascript interface SplitTextOptions { /** 文字大小 **/ fontSize?: number; /** 字体 **/ fontFamily?: string; /** 单行宽度 **/ maxWidth?: number; /** 缩进字数 **/ textIndent?: number; /** 是否每段分割 **/ isSplit?: boolean; /** 父级dom **/ parentDom?: HTMLElement; } export function splitText(text: string | string[], config?: SplitTextOptions, wrapText?: string | string[]) { let _parentDomWidth = 0; if (config && config.parentDom) { _parentDomWidth = config.parentDom.getBoundingClientRect().width; } let _config = Object.assign({ fontSize: 18, maxWidth: _parentDomWidth || 900, textIndent: 0, isSplit: true, fontFamily: 'inherit', parentDom: document.body }, config || {}); let _wrapText = Array.from(new Set([ ...[',', '。', '、', ';', ':', '?', '!', '(', ')'], ...(wrapText ? (Array.isArray(wrapText) ? wrapText : [wrapText]) : []) ]) ); let _spanDom = document.createElement('span'); _spanDom.style.fontSize = _config.fontSize + 'px'; _config.parentDom.appendChild(_spanDom); let _text = typeof text === 'string' ? [text] : text; let _ps: {value: string, length: number, isStart?: boolean, isEnd?: boolean}[] = []; for (let i = 0; i < _text.length; i++) { if (_config.isSplit && (i !== 0)) _ps.push({value: '', length: 0}); let _isStart: boolean = true; let _temp: string[] = []; let _w = 0; for (let k = 0; k < _text[i].length; k++) { // 首行缩进 if (_w === 0 && _config.textIndent && _isStart) _w += _config.textIndent * _config.fontSize; if (_text[i].charCodeAt(k) > 255) { _w += _config.fontSize; } else { _spanDom.innerHTML = _text[i][k] === ' ' ? ' ' : _text[i][k]; _w += _spanDom.getBoundingClientRect().width; } if (_w > _config.maxWidth) { while (_text[i][k] && _wrapText.includes(_text[i][k])) { _temp.pop(); k--; } _ps.push({value: _temp.join(''), length: _temp.length, isStart: _isStart}); _temp = []; _isStart = false; _w = 0; k--; } else { _temp.push(_text[i][k]); if (k === _text[i].length - 1) _ps.push({value: _temp.join(''), length: _temp.length, isStart: _isStart, isEnd: true}); } } } _spanDom.remove(); return _ps; } ``` 标签: none 本作品采用 知识共享署名-相同方式共享 4.0 国际许可协议 进行许可。