折叠展开动画而不转换`height`属性?

时间:2019-07-15 17:28:51

标签: javascript html css reactjs styled-components

我读了很多文章,说如果想要平滑的CSS过渡,应该坚持使用transformopacity

例如:https://www.netcentric.biz/insights/2017/09/css-transition-performance.html

核心思想始终似乎是:

  

...为了优化您的过渡体验,浏览器应确保动画CSS不会引起重新绘制。

问题

我需要执行以下代码段操作:用户单击时展开/折叠过滤器框。到目前为止,我只能通过转换它们的height属性来做到这一点。我可以通过其他方式执行此操作而无需像以前那样转换height属性吗?


注意:这是一个移动视图,我确实希望FiltersResults打开时向下“推”。结果将是一个包含30种产品的画廊,其中包含缩略图,标题和链接。

const styled = window.styled;

const Header_DIV = styled.div`
  position: fixed;
  top: 0; left: 0;
  width: 100%;
  height: 50px;
  background-color: lightblue;
`;

const Main_DIV = styled.div`
  padding-top: 42px;
`;

const Filters1_DIV = styled.div`
  width: 100%;
  background-color: lightgreen;
  cursor: pointer;
  height: ${props => props.open ? '100px' : '16px' };
  transition: height ease-out .5s;
`;

const Filters2_DIV = styled.div`
  width: 100%;
  background-color: lightcoral;
  cursor: pointer;
  height: ${props => props.open ? '100px' : '16px' };
  transition: height ease-out .5s;
`;

const Results_DIV = styled.div`
  background-color: lightgray;
`;

function App() {
  
  const [openFilter1,setOpenFilter1] = React.useState(false);
  const [openFilter2,setOpenFilter2] = React.useState(false);
  
  function toggleFilter1() {
    setOpenFilter1((prevState) => !prevState);  
  }
  
  function toggleFilter2() {
    setOpenFilter2((prevState) => !prevState);  
  }
  
  return(
    <React.Fragment>
      <Header_DIV>
        Header
      </Header_DIV>
      <Main_DIV>
        <Filters1_DIV
          onClick={toggleFilter1}
          open={openFilter1}
        >
          Filter1 ----------- Click to open/close!
        </Filters1_DIV>
        <Filters2_DIV
          onClick={toggleFilter2}
          open={openFilter2}
        >
          Filter2 ----------- Click to open/close!
        </Filters2_DIV>
        <Results_DIV>
          Results
        </Results_DIV>
      </Main_DIV>
    </React.Fragment>
  );
}

ReactDOM.render(<App/>, document.getElementById('root'));
* {
  box-sizing: border-box;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.3/umd/react-dom.production.min.js"></script>
<script src="//unpkg.com/styled-components/dist/styled-components.min.js"></script>
<div id="root"/>

1 个答案:

答案 0 :(得分:1)

您可以尝试将transform: scale(0)opacity: 0一起使用。但是您可能需要稍微调整一下布局和样式。