|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 |
如何固定列宽下数字过长时:先继承父级字号,再按设计稿字号逐步 -1 缩小,最小 12;仍超出才 `...`。 适配约定(375 设计稿): - `html.fontSize = (width / 375) * 100` - postcss `rootValue: 100` → 设计稿 px 转 rem:`px / 100` --- ## 封装:AutoFitText ```tsx import { useLayoutEffect, useRef, type ReactNode } from 'react' /** * 与 index.html / postcss-pxtorem 一致: * - 设计稿 375 * - html fontSize = (width / 375) * 100 * - 设计稿 px → rem:px / 100 */ const DESIGN_ROOT_VALUE = 100 const MIN_DESIGN_FONT_SIZE = 12 interface AutoFitTextProps { children: ReactNode className?: string } const designPxToRem = (designPx: number) => `${designPx / DESIGN_ROOT_VALUE}rem` /** 数字列可用宽度 = 父容器宽 - 兄弟节点宽 - 自身 margin(不改动外部 flex 布局) */ const resolveConstraintWidth = (el: HTMLElement): number => { const parent = el.parentElement if (!parent) return 0 const host = parent.parentElement if (host && host.clientWidth > 0) { let siblingsWidth = 0 const children = host.children for (let i = 0; i < children.length; i += 1) { const child = children[i] as HTMLElement if (child === parent) continue siblingsWidth += child.offsetWidth } const parentStyle = window.getComputedStyle(parent) const margin = (parseFloat(parentStyle.marginLeft) || 0) + (parseFloat(parentStyle.marginRight) || 0) const next = host.clientWidth - siblingsWidth - margin if (next > 0) return next } return parent.clientWidth > 0 ? parent.clientWidth : el.clientWidth } /** * 默认继承父级字号;超出后按设计稿字号逐步 -1 缩小, * 最小 12;仍超出再省略号。 */ export const AutoFitText = ({ children, className }: AutoFitTextProps) => { const ref = useRef<HTMLSpanElement>(null) useLayoutEffect(() => { const el = ref.current if (!el) return const parent = el.parentElement let cancelled = false let rafId = 0 const fit = () => { if (cancelled) return el.style.fontSize = '' el.style.maxWidth = '' el.classList.remove('is-ellipsis') const constraint = resolveConstraintWidth(el) if (constraint <= 0) return // 仅约束自身测量,不改父级 flex,避免把「股」等兄弟顶飞 el.style.maxWidth = `${constraint}px` if (el.scrollWidth <= constraint + 1) { el.style.maxWidth = '' return } const rootPx = parseFloat( window.getComputedStyle(document.documentElement).fontSize, ) || DESIGN_ROOT_VALUE const inheritedCssPx = parseFloat(window.getComputedStyle(el).fontSize) || 14 let designSize = Math.round((inheritedCssPx / rootPx) * DESIGN_ROOT_VALUE) while ( designSize > MIN_DESIGN_FONT_SIZE && el.scrollWidth > constraint + 1 ) { designSize -= 1 el.style.fontSize = designPxToRem(designSize) } if (el.scrollWidth > constraint + 1) { el.classList.add('is-ellipsis') } else { // 缩到能放下后去掉 maxWidth,避免多余裁切 el.style.maxWidth = '' } } const scheduleFit = () => { if (rafId) window.cancelAnimationFrame(rafId) rafId = window.requestAnimationFrame(fit) } fit() scheduleFit() window.addEventListener('resize', scheduleFit, false) let resizeObserver: ResizeObserver | null = null if (typeof ResizeObserver !== 'undefined') { resizeObserver = new ResizeObserver(scheduleFit) if (parent) resizeObserver.observe(parent) if (parent?.parentElement) resizeObserver.observe(parent.parentElement) } const fonts = document.fonts if (fonts?.ready) { void fonts.ready.then(() => { if (!cancelled) scheduleFit() }) } return () => { cancelled = true if (rafId) window.cancelAnimationFrame(rafId) window.removeEventListener('resize', scheduleFit, false) resizeObserver?.disconnect() } }, [children]) return ( <span ref={ref} className={`trade-order-bottom__auto-fit-text${ className ? ` ${className}` : '' }`} > {children} </span> ) } ``` 配套样式: ```less &__auto-fit-text { display: block; width: 100%; min-width: 0; overflow: hidden; font-size: inherit; line-height: inherit; color: inherit; font-family: inherit; white-space: nowrap; text-overflow: clip; &.is-ellipsis { text-overflow: ellipsis; } } /* 容器必须有固定宽度,文字节点占满宽度,才能正确测溢出 */ .demo-box { width: 120px; overflow: hidden; font-size: 16px; > span { display: block; width: 100%; max-width: 100%; overflow: hidden; white-space: nowrap; } } ``` --- ## 使用案例(独立 Demo) ```tsx import { useState } from 'react' import { AutoFitText } from './auto-fit-text' export default function AutoFitTextDemo() { const [text, setText] = useState('12345678901234567890') return ( <div> <input value={text} onChange={(e) => setText(e.target.value)} placeholder="输入一段文字试试" /> {/* 固定 120px 宽,观察字号缩小 / 省略号 */} <div className="demo-box"> <AutoFitText>{text}</AutoFitText> </div> </div> ) } ``` 效果说明: 1. 输入较短内容:保持父级 `16px` 2. 内容变长:字号逐步降到 `15 → 14 → … → 12` 3. 到 `12` 仍放不下:显示 `...` --- ## 注意点 1. 父容器要有明确宽度,且 `overflow: hidden` 2. 文字节点 `width: 100%` + `white-space: nowrap`,否则 `scrollWidth === clientWidth` 测不准 3. 缩小后写 rem(`设计稿px / 100`),不要写死 `px` 4. 未缩小时清空内联 `fontSize`,继续继承父级字号 |
