要实现文本超过两行后,自动缩小字号以适应内容的效果,可以使用CSS的@supports规则结合JavaScript来实现。
.container {
display: flex;
flex-direction: column;
max-height: 3.6em; /* 2行文字高度 * 字号 */
overflow: hidden;
}
.container p {
display: -webkit-box;
-webkit-box-orient: vertical;
overflow: hidden;
text-overflow: ellipsis;
/* 支持 line-clamp 的浏览器 */
@supports (-webkit-line-clamp: 2) or (line-clamp: 2) {
-webkit-line-clamp: 2;
line-clamp: 2;
-webkit-box-pack: center;
-webkit-box-align: end;
font-size: 16px; /* 初始字号 */
transition: font-size 0.2s;
}
}
import React, { useEffect, useRef } from 'react';
function MyComponent() {
const containerRef = useRef(null);
const textRef = useRef(null);
let fontSize = 16;
useEffect(() => {
const container = containerRef.current;
const text = textRef.current;
const adjustFontSize = () => {
while (text.scrollHeight > container.offsetHeight) {
fontSize--;
text.style.fontSize = `${fontSize}px`;
if (fontSize <= 10) {
break;
}
}
};
adjustFontSize();
}, []);
return (
<div className="container" ref={containerRef}>
<p ref={textRef}>Hello World</p>
</div>
);
}