开启掘金成长之旅!这是我参与「掘金日新计划 · 12 月更文挑战」的第8天,点击查看活动详情
前言:
成功没有捷径但成长有路径
css必备场景。专注积累,每天记录一个知识点,老概念新理解,重点记录一下
每天梳理一个场景,知识点查漏补缺,充实满足。
正文
背景
在上面几篇文章中介绍了css可在多行内容实现省略,但是一般不能只用他来实现,css会在未超出的情况也出现省略,需要结合js判断是否需要内容省略。设计的要求有时候会很多变,而且有兼容性问题,有时候写的一种方法并不会兼容所有情况。这篇文章介绍下一种通用的写法,按高度截断的方式,将过多的内容隐藏而显示部分,比如设置超过两行即省略。
实现
offsetHeight 高度截断
JS的基本思路是通过获取样式中设置的line-height属性,获取到值以后,根据(传入的限制行数*line-height) 来计算展示区文本高度。然后根据实际文本内容的高度是否大于计算出的限制高度,来判断是否显示省略。
const height = parseInt(getComputedStyle(multiRow.current).height);
const lineHeight = parseInt(getComputedStyle(multiRow.current).lineHeight);
if (height > lineHeight * 2) {
// 设置省略
}
.ellipsis_wrap{
overflow: hidden;
word-break: break-all;
text-overflow: ellipsis;
-webkit-line-clamp: 2;
display: -webkit-box;
-webkit-box-orient': vertical;
}
const Ellipsis = (props) => {
const { children, ...other } = props;
const [needMore, setNeedMore] = useState(false);
const [showDescription, setShowDescription] = useState(false);
const [popWidth, setPopWidth] = useState();
const multiRow = useRef(null);
useEffect(() => {
const height = parseInt(getComputedStyle(multiRow.current).height);
const lineHeight = parseInt(getComputedStyle(multiRow.current).lineHeight);
if (height > lineHeight * 2) {
setPopWidth(multiRow.current.clientWidth);
setShowDescription(true);
setNeedMore(true);
}
}, [children]);
return needMore ? (
<Balloon
closable={false}
followTrigger
popupStyle={{ maxWidth: popWidth }}
trigger={
<div
style={{ '-webkit-box-orient': 'vertical' }}
className={showDescription ? 'ellipsis_wrap' : ''}
ref={multiRow}
>
{children}
</div>
}
{...other}
>
{children}
</Balloon>
) : (
<div
ref={multiRow}
style={{ '-webkit-box-orient': 'vertical' }}
className={showDescription ? 'ellipsis_wrap' : ''}
>
{children}
</div>
);
};
export default Ellipsis;
总结
有些东西纯看是没用的,必须上手走一遍才会清楚明白,记忆也更深刻。因为参加更文挑战,开始一些迷迷糊糊的知识点,也开始清楚明白起来。现在的规划是更新基础知识,等逻辑理顺了,再将以前只是在脑子里有雏形的想法记录成文章,修整成完整的项目。