As shown in the figure, an ellipse appears in the middle of the text;
1. Demand
There may be this demand: when the text contains a suffix, the product requires that when the length exceeds, the suffix and the preceding part are displayed, and an ellipsis appears in the middle.
2. Solution ideas
dom
You can create two new elements in the current module , prev
and next
use the string slice
method to intercept
3. Code implementation
1.Code tsx
_
/*
* @Author: risheng
* @Date: 2022-06-16 14:16:31
* @LastEditTime: 2022-06-16 14:31:05
* @Description:
* @FilePath: /vite-project/src/modules/testEllipsis.tsx
*/
import React, {
useState } from 'react';
import '../less/index.less';
export const Ellipsis = () => {
const [strArr] = useState<string[]>(['1655360455000.jpeg', '20220616.jpeg', 'test.png', '这是测试字符串.png', '点赞.png']);
return (
<div className='parent-top'>
{
strArr.map((item: string) => {
return (
<div className="parent">
{
item.length > 10
? (
<div className='parent-main'>
<span className='prev-span'>{
item.slice(0, -6)}</span>
<span className='next-span'>{
item.slice(-6)}</span>
</div>
)
: item
}
</div>
)
})
}
</div>
)
}
2.Code Less
_
.parent{
width: 100px;
height: 36px;
line-height: 36px;
margin: 0 auto;
text-align: left;
border: 1px solid;
margin-bottom: 20px;
.parent-main{
width: 100%;
height: 36px;
display: flex;
overflow: hidden;
.prev-span{
display: block;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
.next-span{
display: block;
white-space: nowrap;
}
}
}
3. Analysis
parent
class is the parent element- When the length of the elements
strArr
in exceeds 10, the string is split. I split it according to -6, add a parent module forflex
layout, and two sub-modules. The first one sets the overflow ellipsis display, and the second one Set no line wrapping - If the length does not exceed 10, no operation will be performed.