【问题标题】:How to prevent a column to grow in a grid if an element is dynamically added to it?如果动态添加元素,如何防止列在网格中增长?
【发布时间】: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


    【解决方案1】:
    import styled from "styled-components";
    
    const Button = styled.button`
      opacity: 0;
    `;
    
    const Root = styled.div`
      display: flex;
      align-items: center;
      justify-content: space-between;
      background: orange;
      padding: 0 12px;
    
      :hover {
        ${Button} {
          opacity: 1;
        }
       }
      `;
    
     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 }) {
     return (
    <Root>
      <Title>{title}</Title>
      <Button>edit</Button>
    </Root>
    );
    }
    

    【讨论】:

    • 嗨@Serj!这不是最喜欢的解决方案,因为它意味着在有足够空间显示的标题上执行早期省略号。从 ui 的角度来看,这很奇怪。
    • 嗨@Serj。你应该在你的答案前加上一个简短的解释,说明它的作用以及为什么这是你认为应该解决的方式。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多