CSS & JS Effect – fade in

参考:

stackoverflow – Is there a CSS-only (pure CSS) workaround to apply fade-in and fade-out on objects with display:none?

 

思路和难点

最简单的思路就是 opacity 0 到 1, 配上 transition. 但它的问题是 opacity 是透明, 元素依然占据位置, 而且还可以被 hover.

那加上 visibility: hidden 呢? 如果是在 absolute element 通常就可以了. 虽然它依然占据空间, 但至少不能 hover 了. 

再极端一点就只能加上 height: 0 来抵消空间了. 要留意 height: 0 的冷知识 哦.

display: none 是绝对不能用的, 因为它没有 transition.

最后真的搞不定就用 JS 吧.

 

实现

效果

HTML

<div class="menu-trigger">
  <span>Services</span>
  <div class="box">
    <div class="item">item1</div>
    <div class="item">item2</div>
    <div class="item">item3</div>
    <div class="item">item4</div>
  </div>
</div>

CSS Style

.menu-trigger {
  width: max-content;
  position: relative;
  padding: 1rem 0;

  .box {
    position: absolute;
    width: max-content;
    top: 120%;
    left: 0;

    .item {
      padding: 1rem 1rem;
      background-color: pink;
    }

    opacity: 0;
    visibility: hidden;
    transition-property: opacity, top, visibility;
    transition-duration: 0.4s;
  }

  &:hover {
    .box {
      opacity: 1;
      top: 100%;
      visibility: visible;
    }
  }
}

只是用了 visibility + opacity

 

posted @ 2022-03-02 17:32  兴杰  阅读(91)  评论(0)    收藏  举报