CSS & JS Effect – Loading Button

效果

一个按钮, 点击以后中间出现 loading, 然后旋转.

 

思路

1. 监听点击, hide text, show loading

2. loading 定位中心

3. loading 是通过 border + radius 做出来的, 然后 animation 让它无限 rotate

 

难点

1. button 的 width 是依据 text 的 width, 当 width hide 的时候要保留它的空间.

2. loading 的比例是 1:1, 它的 dimension 需要占据整个 button 的高度 (扣除 padding-block)

 

实现代码

HTML

<button>
  <span>Submit</span>
</button>

loading 用 ::after 来完成, 所以只有 text 需要 element

Style CSS

复制代码
   button {
      $button-padding-block: 2rem;

      border-width: 0; // reset CSS
      cursor: pointer; // base CSS
      background-color: hsl(203, 97%, 54%);
      color: white;
      border-radius: 10px;
      padding: $button-padding-block 3rem;
      font-size: 4rem;

      // 当有 loading class 时
      &.loading {
        // hide text (要保留空间, 所以用 visibility)
        span {
          visibility: hidden;
        }

        position: relative;
        &::after {
          $loading-border-top: 0.5rem;
          content: '';

          // dimension
          aspect-ratio: 1 / 1;
          height: 50%;

          // 定位居中
          position: absolute;
          top: 50%;
          left: 50%;
          transform: translate(-50%, -50%);

          // 1 边圆角
          border: $loading-border-top solid transparent;
          border-top-color: red;
          border-radius: 50%;

          // 旋转
          animation: spin 1s infinite;
          @keyframes spin {
            from {
              transform: translate(-50%, -50%) rotate(0);
            }
            to {
              transform: translate(-50%, -50%) rotate(360deg);
            }
          }
        }
      }
    }
复制代码

注: 上面用了 aspect-ratio 来实现, 无法使用 padding-top 模拟的 aspect-ratio 因为这里需要 depend on height.

JS

const button = document.querySelector("button");
button.addEventListener("click", () => {
  button.classList.toggle("loading");
});

 

posted @   兴杰  阅读(166)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 在鹅厂做java开发是什么体验
· 百万级群聊的设计实践
· WPF到Web的无缝过渡:英雄联盟客户端的OpenSilver迁移实战
· 永远不要相信用户的输入:从 SQL 注入攻防看输入验证的重要性
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
点击右上角即可分享
微信分享提示