作者:咕魂
日期:2025年1月13日
目录
注意事项
- 不要给svg加style属性,会导致实际布局与图片布局不一致
- 不要使用overflow:hidden属性,文本超出长度转换为省略号将无法使用
- // 替换方案
- // js限制字符串长度
- formatStr(text) {
- let maxLength = 20;
- switch(this.col){
- case 2:
- maxLength = 20;
- break;
- case 3:
- maxLength = 15;
- break;
- case 4:
- maxLength = 12;
- break;
- case 5:
- maxLength = 10;
- break;
- }
- let currentWidth = 0;
- let truncatedText = '';
- let maxWidth = maxLength * 8;
- for (let char of text) {
- // 判断字符是中文字符(Unicode范围来大致判断)
- let pattern = /[^a-zA-Z0-9.,;:!?\-_@#$%^&*()+=<>{}[\]\/\\|]/;
- if (pattern.test(char)) {
- currentWidth += 13; // 假设中文字符宽度为16px,可根据实际字体调整
- } else {
- currentWidth += 8; // 假设英文字符宽度为8px,可根据实际字体调整
- }
- if (currentWidth <= maxWidth) {
- truncatedText += char;
- } else {
- return truncatedText + '...';
- }
- }
- return truncatedText;
- }
复制代码 来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |