网站首页 > 知识剖析 正文
通过元素宽度和字数计算得到缩放
简单实现如下:
/**
* 字体最大为视觉要求大小(maxFontSize);超出缩小字体显示,最小为minFontSize;最小字体时超出部分使用圆点(...);
* params.minFontSize 最小字体
* params.maxFontSize 最大字体
* params.fontSizeUnit 字体单位
* params.dom 元素节点
*/
const setTextFontSize = (params) => {
const { minFontSize = 12, maxFontSize = 18, fontSizeUnit = "px", dom, ...rest} = params || {};
const textLen = dom?.innerHTML?.trim()?.length;
const domWith = dom?.getBoundingClientRect()?.width;
let initFontSize = Math.floor((domWith) / textLen);
const isCutOff = initFontSize < minFontSize;
if (initFontSize <= minFontSize) {
initFontSize = minFontSize;
} else if (initFontSize >= maxFontSize) {
initFontSize = maxFontSize;
}
initFontSize = fontSizeUnit === "rem" ? initFontSize / 10 : initFontSize;
let styleStr = `font-size:${initFontSize}${fontSizeUnit};`;
if (isCutOff) {
styleStr = `${styleStr}overflow:hidden;white-space:nowrap;text-overflow:ellipsis;`;
}
console.log(textLen,initFontSize,domWith, (domWith) / textLen,textLen,styleStr);
dom.style = styleStr;
}
猜你喜欢
- 2025-04-26 方舟像素字体ArkPixelFont——开源的泛中日韩像素字体
- 2025-04-26 菜鸟级的Obsidian样式调整
- 2025-04-26 网页设计得懂css的规范
- 2025-04-26 PC网站建设免费教程:从入门到精通
- 2025-04-26 13.CSS添加文本样式
- 2025-04-26 十大CSS代码编辑器
- 2025-04-26 10款Web程序员必备的CSS工具
- 2025-04-26 vue项目引入字体文件过大和动态加载文本,字体不生效问题
- 2025-04-26 前端开发,在项目中常用的css样式整理
- 2025-04-26 什么是CSS?
- 最近发表
- 标签列表
-
- xml (46)
- css animation (57)
- array_slice (60)
- htmlspecialchars (54)
- position: absolute (54)
- datediff函数 (47)
- array_pop (49)
- jsmap (52)
- toggleclass (43)
- console.time (63)
- .sql (41)
- ahref (40)
- js json.parse (59)
- html复选框 (60)
- css 透明 (44)
- css 颜色 (47)
- php replace (41)
- css nth-child (48)
- min-height (40)
- xml schema (44)
- css 最后一个元素 (46)
- location.origin (44)
- table border (49)
- html tr (40)
- video controls (49)