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: calc( 100% - ($button-padding-block * 2) - ($loading-border-top * 2) ); // 定位居中 position: absolute; inset: 0; margin: auto; // 1 边圆角 border: $loading-border-top solid transparent; border-top-color: red; border-radius: 50%; // 旋转 animation: spin 1s infinite; @keyframes spin { from { transform: rotate(0); } to { transform: rotate(360deg); } } } } }
上面用了 aspect-ratio 来实现, 无法使用 padding-top 模拟的 aspect-ratio 因为这里需要 depend on height.
JS
const button = document.querySelector("button"); button.addEventListener("click", () => { button.classList.toggle("loading"); });
标签:loading,text,button,top,Effect,padding,Loading,border,Button 来源: https://www.cnblogs.com/keatkeat/p/16103611.html