【发布时间】:2021-05-07 18:50:50
【问题描述】:
我有一个包含几列的网格。每列包含一个带有标题的标题。鼠标悬停时,编辑标题的按钮会附加到标题中。这会导致列增长。
在鼠标悬停时,我想保持相同的列宽,附加按钮,如果标题太长而无法正确附加按钮,则在标题上执行省略号。
当列既不在网格中也不在弹性布局中时,我已经设法实现了这种行为。
如何在网格模板中实现这种行为?列应始终占用可用空间的 1/3,因此我无法指定宽度。
这是代码和沙箱:
// Header
const Root = styled.div`
display: flex;
align-items: center;
justify-content: space-between;
background: orange;
padding: 0 12px;
`;
const Title = styled.h1`
display: inline-block;
max-width: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
word-wrap: normal;
margin-right: 12px;
`;
export default function Header({ title }) {
const [edit, setEdit] = useState(false);
return (
<Root onMouseOver={() => setEdit(true)} onMouseLeave={() => setEdit(false)}>
<Title>{title}</Title>
{edit && <button>edit</button>}
</Root>
);
}
// Grid
const Grid = styled.div`
display: grid;
grid-template-columns: repeat(3, 1fr);
`;
const Col = styled.div`
margin: 12px;
padding: 24px;
`;
export default function App() {
return (
<>
<h1>GRID (not ok)</h1>
<Grid>
<Col>
<Header title="Col 1 long title" />
</Col>
<Col>
<Header title="Col 2" />
</Col>
<Col>
<Header title="Col 3" />
</Col>
</Grid>
<h1>NO GRID (OK)</h1>
<div>
<Col>
<Header title="Col 1 long title" />
</Col>
<Col>
<Header title="Col 2" />
</Col>
<Col>
<Header title="Col 3" />
</Col>
</div>
</>
);
}
沙盒:https://codesandbox.io/s/dynamic-text-ellipsis-78vbw?file=/src/App.tsx:72-800
感谢您的帮助!
【问题讨论】:
标签: javascript css reactjs ellipsis