css之實現下拉框自上而下展開動畫效果&&自下而上收起動畫效果


HTML代碼:

<div
        className={CX('font-size-selector-sub-list', {
          show: shouldSubListShow === true,
          hidden: shouldSubListShow === false,
        })}
      >
        {
          subListItems.map((item, index) => {
            return (
              <div
                role="button"
                tabIndex={0}
                key={item}
                className="font-size-selector-sub-items"
                onClick={() => { handleClickSubItem(index) }}
              >
                <div className="font-size-selector-span">{item}</div>
              </div>
            )
          })
        }
      </div>

CSS代碼:

@keyframes slide-down{
    0%{transform:scale(1,0);}
    100%{transform:scale(1,1);}
  }

  @-webkit-keyframes slide-down{
    0%{-webkit-transform:scale(1,0);}
    100%{-webkit-transform:scale(1,1);}
  }

  .font-size-selector-sub-list {
    position: absolute;
    top: 21px;
    left: 0;
    width: 100%;
    box-sizing: border-box;
    z-index: 1;
    box-shadow: 0 2px 4px 0 rgba(0, 0, 0, 0.5);
    background-color: #ffffff;
    border-radius: 2px;
    cursor: pointer;

    .font-size-selector-sub-items {
      padding: 0 6px;
      height: 19px;
      box-sizing: border-box;
      background-color: #ffffff;
      background-repeat: no-repeat;
      display: flex;
      justify-content: space-between;
      align-items: center;

      &:hover {
        background-color: #d3edfb;
      }
    }
  }

  .show {
    max-height: 114px;
    transition: max-height .3s ease-in;
    transform-origin: 50% 0;
    animation: slide-down 0.3s ease-in;
    -webkit-animation: slide-down 0.3s ease-in;
  }

  .hidden {
    max-height: 0px;
    overflow: auto;
    transition: max-height .3s ease-out;
  }

注意點:

1,自上而下展開效果:transition與animation結合使用。如上:.show

2,自下而上收起效果:transition單獨使用。如上:.hidden

首先想到的是在收起和展開兩個終點位置改變 max-height,然后均加上transition,但是這樣做只能實現下拉框父元素收起和展開,內部子元素高度變不了,所以想到加上overflow:auto/hidden,但是這樣又只能對收起起作用,展開無作用,原因是,展開時子元素內容高度小於等於父元素展開時設置的max-height,所以針對展開,需要使用transform:scale();屬性,這樣可以在展開時,讓子元素內容慢慢縮放至父元素的高度。需要注意的是,縮放時要設置 transform-origin: 50% 0;分別表示x,y開始縮放位置。

另外可以參考:https://blog.csdn.net/web_hwg/article/details/68925003


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM